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.