[英]Grab a website with PHP and then traverse it with jQuery
我正在構建一個系統,我需要用PHP抓取網頁的內容,然后解析它以提取某些表等。有一個簡單的方法用jQuery做這個或者最好的方法是編寫PHP提取數據的功能?
jQuery與PHP無關,無法在沒有瀏覽器的情況下運行,所以你在那里運氣不好。
但是,有一個phpQuery允許使用jQuery的選擇器進行DOM解析!
在php中使用本機php DOM函數和xpath這樣做:
$dom = new DOMDocument();
@$dom->loadHTML($html);
$x = new DOMXPath($dom);
// grab all tables with id of foo
foreach($x->query("//table[@id='foo']") as $node)
{
// here is the html
echo $node->c14n();
// grab the containing text
echo $node->textContent()
}
您可以使用PHP http://php.net/manual/en/book.dom.php中提供的DOM函數
你不能。 jQuery適用於JavaScript,它是客戶端,需要JavaScript引擎才能執行。
我建議您將HTML讀作XML,但如果HTML不是XHTML有效,您將遇到各種麻煩。
這太棒了
http://sourceforge.net/projects/simplehtmldom/
例:
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
有一些PHP軟件包可以幫助你,curl,dom和xpath。
這是我以前用過的一個很好的教程 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.