2011-08-31 54 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