2013-04-26 51 views
1
<tr class='Jed01'> 
<td height='20' class='JEDResult'>1</td> 
<td height='30' class='JEDResult'>26.04.2013</td> 
<td height='30' class='JEDResult'>19:43</td> 
<td height='30' class='JEDResult'>Processing</td> 
<td height='30' class='JEDResult'><a href="#" pressed="GetInfo(1233);" title=''>Jeddah</a></td> 
</tr> 

結果=第一步 - 日期 - 時間 - 狀態 - 地方DOM解析問題空的結果

首先,我是新來的PHP,我試圖通過PHP這個數據解析到我的網頁 - DOM正如在Stackoverflow之前向我推薦的那樣。在下面的代碼中,我調用了所有的類來獲取數據,但在沒有任何問題的時候我無法得到任何結果。那麼請問哪裏可能是我的問題?

由於從現在

<?php 

$input = "www.kalkatawi.com/luai.html" 
$html = new DOMDocument(); 
$html->loadHTML($input); 


foreach($html->getElementsByTagName('tr') as $tr) 
{ 
    if($tr->getAttribute('class') == 'Jed01') 
    { 
    foreach($html->getElementsByTagName('td') as $td) 
    { 
     if($td->getAttribute('class') == 'JEDResult') 
     { 
     echo ($td->nodeValue); 
     } 
    }  
    } 
} 

?> 
+2

你必須在第一行代碼的一些語法錯誤更容易做到這一點:'$輸入= 'myLink的';'' – Sirko 2013-04-26 09:14:44

+0

預計loadHTML''$輸入*本身*爲HTML,在你的例子中它不是。這是怎麼回事? – Jon 2013-04-26 09:17:54

+0

不知道如何從作者看到這種語法錯誤?寫在記事本上? – 2013-04-26 09:18:09

回答

2

不要忘記那些半冒號;)

試試這個;

<?php 

$input = file_get_contents("http://www.kalkatawi.com/luai.html"); 
$html = new DOMDocument(); 
$html->loadHTML($input); 


foreach($html->getElementsByTagName('tr') as $tr) 
{ 
    if($tr->getAttribute('class') == 'Jed01') 
    { 
    foreach($tr->getElementsByTagName('td') as $td) 
    { 
     if($td->getAttribute('class') == 'JEDResult') 
     { 
     echo ($td->nodeValue); 
     echo '<br/>'; 
     } 
    }  
    } 
    echo '<br/><br/>'; 
} 

?> 

應輸出;

1 
26.04.2013 
19:43 
Processing 
Jeddah 


2 
26.04.2013 
20:43 
Printed 
RIY 
+0

謝謝我已編輯但沒有發生。如果您想查看,我還添加了我的鏈接。再次感謝 – 2013-04-26 09:41:11

+0

@路易:我編輯了我的代碼,試試。 – Dom 2013-04-26 09:47:59

+0

感謝它在添加'file_get_contents'之後現在可以工作。 – 2013-04-26 09:54:55

1

這段代碼有幾個問題。

加載HTML

$input = 'MyLink'; 
$html = new DOMDocument(); 
$html->loadHTML($input); 

此代碼試圖把字符串'MyLink'爲HTML,這顯然是不。如果這是你的實際代碼,那麼除了這一點,沒有什麼可以工作。請提供正確的HTML輸入或使用loadHTMLFile從文件加載HTML。

比較是區分大小寫的

一方面,有這樣的:

<tr class='Jed01'> 

,而在另一這樣的:

if($tr->getAttribute('class') == 'JED01') 

由於'Jed01' = 'JED01'這個意志!永遠不會是true。要麼固定外殼,要麼使用其他機制(如stricmp)來比較類。

對象不能打印

這將導致一個致命錯誤:

echo ($td); 

應然相反:最有可能echo $td->nodeValue,但其他可能性是開放取決於你想要做什麼。

但是你可以使用XPath

$xpath = new DOMXPath($html); 
$query = "//tr[@class='Jed01']//td[@class='JEDResult']"; // google XPath syntax 

foreach ($xpath->query($query) as $node) { 
    print_r($node->nodeValue); 
} 
+0

感謝您的回答喬恩。我從JEF01編輯Jed01和回聲,但沒有改變。再次感謝我需要幫助。 – 2013-04-26 09:47:41