2012-07-13 85 views
2

爲什麼這會返回整個html文檔,而不僅僅是包含「H + R + E」節點的值? HTML的php xpath返回整個html

樣本:

<tr class="linesAlt1"> 
     <td>04:10 PM</td><td style="width:53%;">3055&nbsp;Over</td><td style="width:22%;">3&nbsp;H+R+E&nbsp;&nbsp;+146</td> 
    </tr> 

我只想得到"3&nbsp;H+R+E&nbsp;&nbsp;+146"。但是這會轉儲所有的html。

<?php 

$url = 'http://www.pinnaclesports.com/ContestCategory/MLB+Propositions/July+13~2C~+2012/Lines.aspx'; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
$html = curl_exec($ch); 
curl_close($ch); 

$doc = new DOMDocument(); 
$doc->loadHTML($html); 
$xpath = new DOMXPath($doc); 

foreach ($xpath->query("//table/tr/td[contains(., 'H+R+E')]") as $textNode){ 
    echo $textNode->nodeValue."\n"; 
} 


?> 
+0

可能與命名空間有關嗎? 「<!DOCTYPE html PUBLIC」 - // W3C // DTD XHTML 1.0 Transitional // EN「」http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd「> 「 – sayhey69 2012-07-13 22:53:12

回答

0

curl_exec打印到STDOUT默認情況下,這是你所看到的。換句話說,你不會捕獲任何輸出$html(或在該循環中打印任何東西)。首先,你需要將輸出重定向:

curl_setopt($ch, CURLOPT_FILE, fopen('php://stdout', 'w')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_URL, $url); 
$html = curl_exec($ch); 

修復該問題後,我看着提供的URL的來源和無法找到文本 - H+R+E - 在任何地方。它有一張桌子,但沒有那個內容。你正在尋找一些不在那裏的東西。

爲了證明它現在可以正確地檢索文件,試試這個完整的例子:

$url = 'http://www.pinnaclesports.com/ContestCategory/MLB+Propositions/July+13~2C~+2012/Lines.aspx'; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_FILE, fopen('php://stdout', 'w')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_URL, $url); 
$html = curl_exec($ch); 
curl_close($ch); 

$doc = new DOMDocument(); 
$doc->loadHTML($html); 
$xpath = new DOMXPath($doc); 

foreach ($xpath->query("//table") as $table){ 
     echo "[" . $table->nodeValue . "\n"; 
} 

...這會產生以下輸出(loadHTML警告略):

 
[ 
        Client ID: 




        Password: 

有關的更多信息設置捲曲選項:

+0

謝謝。我意識到發佈後的源代碼是一個不好的例子,因爲他們在晚上取消了這些信息......不知道我會如何解釋這一點,除非我剛剛從今天早些時候複製整個源。 – sayhey69 2012-07-14 04:36:01