2014-06-27 31 views
0

我嘗試學習捲曲使用,但我不明白它是如何工作的。我如何使用curl(或其他函數)訪問表的一個(頂部)數據條目。到目前爲止,我只能夠檢索整個網站。我怎麼能回聲整個表,特別是第一個條目。我的代碼是:從另一個網站的html表中檢索單行?

<?php 
$ch = curl_init("http://www.w3schools.com/html/html_tables.asp"); 

curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_HEADER, 0); 

curl_exec($ch); 
curl_close($ch); 
?> 
+1

http://www.php.net/manual/en/class.domdocument.php –

回答

2

使用curl是一個良好的開端,但它不會是不夠的,因爲手帕建議,你也需要使用DOMDocument,你也可以包括DOMXpath

示例代碼:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, 'http://www.w3schools.com/html/html_tables.asp'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
libxml_use_internal_errors(true); 
$html = curl_exec($ch); // the whole document (in string) goes in here 
$dom = new DOMDocument(); 
$dom->loadHTML($html); // load it 
libxml_clear_errors(); 
$xpath = new DOMXpath($dom); 
// point it to the particular table 
// table with a class named 'reference', second row (first data), get the td 
$table_row = $xpath->query('//table[@class="reference"]/tr[2]/td'); 
foreach($table_row as $td) { 
    echo $td->nodeValue . ' '; 
} 

應該輸出:

Jill Smith 50 
+0

如何呼應它在相同的格式,意思是,Jill會在左邊,Smith在中間,在同一排的右邊50。 – user3517904

+0

@ user3517904好吧,只需省略'
',或者用'''替換它(空格) –

+0

@ user3517904肯定沒問題! –