当前位置:首页 > PHP教程 > PHP常见问题

phpQuery让php处理html代码像jQuery一样方便

简介

如何在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 drive</span>
        <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 raid</span>
        <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,很方便。



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!