phpQuery让php处理html代码像jQuery一样方便,phpqueryjquery_PHP教程

WBOY
풀어 주다: 2016-07-13 10:10:14
원래의
716명이 탐색했습니다.

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

简介

如何在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

复制代码 代码如下:

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,很方便。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/938850.htmlTechArticlephpQuery让php处理html代码像jQuery一样方便,phpqueryjquery 简介 如何在php中方便地解析html代码,估计是每个phper都会遇到的问题。用phpQuery就可以...
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!