phpQuery讓php處理html代碼像jQuery一樣方便,phpqueryjquery_PHP教程

來源:互聯網
上載者:User

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

複製代碼 代碼如下:



Spiderman City Drive








Spiderman - City Raid





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

http://www.bkjia.com/PHPjc/938850.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/938850.htmlTechArticlephpQuery讓php處理html代碼像jQuery一樣方便,phpqueryjquery 簡介 如何在php中方便地解析html代碼,估計是每個phper都會遇到的問題。用phpQuery就可以...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.