This article mainly introduces phpQuery, which makes it as convenient for php to process html code as jQuery. For more information, see
Introduction
How to easily parse html code in php is probably a problem for every phper. PhpQuery makes it as convenient for php to process html code as jQuery.
Project address: https://code.google.com/p/phpquery/
Github address: https://github.com/TobiaszCudnik/phpquery
DEMO
Download Library File: https://code.google.com/p/phpquery/downloads/list
I'm using onefile: phpQuery-0.9.5.386-onefile.zip
Demo: https://code.google.com/p/phpquery/source/browse/branches/dev/demo.php
And then reference it in the project.
HTML file test.html:
The code is as follows:
Spiderman City Drive
Spiderman-City Raid
Php processing:
The code is as follows:
<? Php
Include ('phpquery-onefile. php ');
$ FilePath = 'test.html ';
$ FileContent = file_get_contents ($ filePath );
$ Doc = phpQuery: newreceiventhtml ($ fileContent );
PhpQuery: selectDocument ($ doc );
$ Data = array (
'Name' => array (),
'Href '=> array (),
'IMG '=> array ()
);
Foreach (pq ('A') as $ t ){
$ Href = $ t-> getAttribute ('href ');
$ Data ['href '] [] = $ href;
}
Foreach (pq ('IMG ') as $ img ){
$ Data ['IMG '] [] = $ domain. $ img-> getAttribute ('src ');
}
Foreach (pq ('. GameName') as $ name ){
$ Data ['name'] [] = $ name-> nodeValue;
}
Var_dump ($ data );
?>
The code above contains the Get attribute and innerText content (obtained using nodeValue ).
Output:
The code is as follows:
Array (size = 3)
'Name' =>
Array (size = 2)
0 => string 'Spiderman City Drive '(length = 20)
1 => string 'Spiderman-City Raid '(length = 21)
'Href '=>
Array (size = 2)
0 => string 'http: // www.gahe.com/Spiderman-City-Drive' (length = 40)
1 => string 'http: // www.gahe.com/Spiderman-City-Raid' (length = 39)
'IMG '=>
Array (size = 2)
0 => string 'http: // www.gahe.com/thumb/12/Spiderman-City-Drive.jpg' (length = 53)
1 => string 'http: // www.gahe.com/thumb/12/Spiderman-City-Raid.jpg' (length = 52)
Powerful is the pq selector. The syntax is similar to jQuery, which is very convenient.