您好,欢迎访问一九零五行业门户网

用phpQuery像jquery一样解析html代码

简介
如何在php中方便地解析html代码,估计是每个phper都会遇到的问题。用phpquery就可以让php处理html代码像jquery一样方便。
项目地址:https://code.google.com/p/phpquery/
github地址:https://github.com/tobiaszcudnik/phpquery
demo
下载库文件:https://code.google.com/p/phpquery/downloads/list
我下的是onefile版:phpquery-0.9.5.386-onefile.zip
官方demo:https://code.google.com/p/phpquery/source/browse/branches/dev/demo.php
然后在项目中引用。
html文件test.html:
div class=thumb id=thumb-13164-3640 style=position: absolute; left: 0px; top: 0px;> a href=/spiderman-city-drive> img src=/thumb/12/spiderman-city-drive.jpg alt=> span class=gamename id=gamename-13164-3640 style=display: none;>spiderman city drivespan> span class=gamerating id=gamerating-13164-3640 style=display: none;> span style=width: 68.14816px;>span> span> a>div>div class=thumb id=thumb-13169-5946 style=position: absolute; left: 190px; top: 0px;> a href=/spiderman-city-raid> img src=/thumb/12/spiderman-city-raid.jpg alt=> span class=gamename id=gamename-13169-5946 style=display: none;>spiderman - city raidspan> span class=gamerating id=gamerating-13169-5946 style=display: none;> span style=width: 67.01152px;>span> span> a>div>
php处理:
php include('phpquery-onefile.php'); $filepath = 'test.html'; $filecontent = file_get_contents($filepath); $doc = phpquery::newdocumenthtml($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);?>
上面的代码中包含了取属性和innertext内容(通过nodevalue取)。
输出:
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)
强大的是pq选择器,语法类似jquery,很方便。
以上就介绍了用phpquery像jquery一样解析html代码,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息