2011-08-31 37 views
0

以下的DOMDocument的結果()調用爲什麼這些跨度不會被domdocument()視爲節點?

$html = <<<EOT 
<div class="list_item"> 
     <div class="list_item_content"> 

      <div class="list_item_title"> 
       <a href="/link/goes/here"> 
        INFO<br /> 
        <span class="part2">More Info</span><br /> 
        <span class="part3">Etc.</span> 
       </a> 
      </div> 

     </div> 
EOT; 

libxml_use_internal_errors(false); 

$dom = new DOMDocument(); 
$dom->loadhtml($html); 
$xpath = new DOMXPath($dom); 

$titles_nodeList = $xpath->query('//div[@class="list_item"]/div[@class="list_item_content"]/div[@class="list_item_title"]/a'); 

foreach ($titles_nodeList as $title) { 
    $titles[] = $title->nodeValue; 
} 

echo("<pre>"); 
print_r($titles); 
echo("</pre>"); 


?> 

Array 
(
    [0] => 
        INFOMore InfoEtc. 

) 

爲什麼包含在結果中的一個元件的內部這兩個跨度數據,當我沒有在路徑中指定這些跨度?我只感興趣的是直接檢索a元素中包含的數據,而不是a元素內跨度中包含的信息。我想知道我做錯了什麼。

+0

SO確實在語法不好的工作突出存在。 – Mike

+0

@Mike是的,語法突出顯示器總是扼殺在PHP中的HEREDOC字符串。 –

+0

@Michael修改它至少突出顯示正確(雖然不能真正修復白色) – cwallenpoole

回答

1

試試這個XPath:

//div[@class="list_item"]/div[@class="list_item_content"]/div[@class="list_item_title"]/a/child::text() 
+0

涼爽,這給了我'陣列 ( [0] => 信息 [1] => )',當我將它修改爲'/ div [@ class =「list_item」]/div [@ class =「list_item_content」]/div [@ class =「list_item_title」]/a/child :: text()[1]'我得到了'Array ( [0] => INFO )'。如果我省略child ::並使用'// div [@ class =「list_item」]/div [@ class =「list_item_content」]/div [@ class =「list_item_title」]/a/text( )[1]'所以我有點困惑,在使用和不使用孩子之間有什麼區別。 – jela

+0

我覺得'text()'只是一個[縮寫](http://www.w3.org/TR/xpath/#path-abbrev)'child :: text()' – stewe

1

節點在那裏,但在瀏覽器中以HTML模式查看它們。嘗試查看網頁源代碼,和/或做:

echo("<pre>"); 
htmlspecialchars(print_r($titles), true); 
echo("</pre>"); 

代替,which'll編碼<>&lt;&gt;,使他們「看得見」。

+0

我看了看源代碼,但它只是'

Array ( [0] => INFOMore InfoEtc. ) 
'並使用htmlspecialchars替換()我得到了'Array ( [0 ] => INFOMore InfoEtc。 )'。雖然我不知道爲什麼,但似乎沒有跨度出現。 – jela

+0

奇數。這是什麼版本的PHP?在5.x上,nodeValue是未公開的.innerHTML等價物。你會得到什麼看起來是.innerTEXT –

+0

PHP版本5.2.6 – jela