2014-09-05 58 views
0

您好,我編寫了以下代碼,以便使用XPATH和curl從表中提取名稱和價格。xpath中非對象錯誤的屬性

<?php 
    include_once ("xpath.php"); 
    header('Content-type: text/html; charset=UTF-8'); 
    $ch = curl_init ("http://emalls.ir/%D9%84%DB%8C%D8%B3%D8%AA-%D9%82%DB%8C%D9%85%D8%AA~Category~39~Search~Nokia"); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    //$page = curl_exec($ch); 
    $page = utf8_decode(curl_exec($ch)); 

    $dom = new DOMDocument(); 
    libxml_use_internal_errors(true); 
    $dom->loadHTML($page); 
    libxml_clear_errors(); 
    $xpath = new DOMXpath($dom); 
    $data = array(); 


    // get all table rows and rows which are not headers 
    $produstname = $xpath->query('//table/tbody/tr/td/a/text()'); 
    $produstprice = $xpath->query('//table/tbody/tr/td[8]/text()'); 
    $data = array(); 
    for ($x=0; $x<=1; $x++){ 
     $data[$x]['title'] = $produstname->item($x)->nodeValue; 
     $data[$x]['price'] = $produstprice->item($x)->nodeValue; 
    } 
    ?> 

這些以下兩個XPATH在鉻上工作以獲取名稱和價格。

name: $x("//table/tbody/tr/td/a/text()") 
price: $x("//table/tbody/tr/td[5]/text()") 

但當下面的代碼使用給這個錯誤

: Trying to get property of non-object in 
+1

* 「在......」 *什麼?懸念正在扼殺我 – Phil 2014-09-05 05:59:46

+0

難道可能,也許,有沒有20個元素符合你的XPath查詢? – Phil 2014-09-05 06:01:08

+0

當我編寫1 elment給出這個錯誤。 – 2014-09-05 06:02:54

回答

1

我見過的現場,我謙恭地建議針對id=""屬性來代替。你也可以使用foreach。例如:

$ch = curl_init ("http://emalls.ir/%D9%84%DB%8C%D8%B3%D8%AA-%D9%82%DB%8C%D9%85%D8%AA~Category~39~Search~Nokia"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); 
$page = curl_exec($ch); 
$page = utf8_decode(curl_exec($ch)); 

$dom = new DOMDocument('1.0', 'utf-8'); 
libxml_use_internal_errors(true); 
$dom->loadHTML($page); 
libxml_clear_errors(); 
$xpath = new DOMXpath($dom); 

$data = array(); 
$table_rows = $xpath->query('//table[@id="grdprice"]/tr'); // target the row (the browser rendered <tbody>, but actually it really doesnt have one) 

if($table_rows->length <= 0) { // exit if not found 
    echo 'no table rows found'; 
    exit; 
} 

foreach($table_rows as $tr) { // foreach row 
    $row = $tr->childNodes; 
    if($row->item(0)->tagName != 'th') { // avoid headers 
     $data[] = array(
      'name' => trim($row->item(0)->nodeValue), 
      'price' => trim($row->item(7)->nodeValue), 
     ); 
    } 
} 

echo '<pre>'; 
print_r($data); 

Sample Output

+0

Thank's.You是一個專業的PHP。爲什麼$ data [] ..是空的 – 2014-09-05 06:09:21

+0

@amirrasabeh謝謝你的補充,但不,我甚至沒有抓過PHP的表面,還有很長的路要走 – Ghost 2014-09-05 06:11:57

+1

@amirrasabeh這只是簡單地說如果你不明確地把一個索引放在賦值上,它會將它追加到數組的末尾 – Ghost 2014-09-05 06:12:50

相關問題