2013-04-02 41 views
2

我檢查,並在許多例子的XPath文本不起作用

following-sibling::text()[1] 

給出一個正確的答案強大的標籤後,接收文本。我打上文字我感興趣的有星號:

<?php 
    $html=' 
     <html> 
     <head> 
     </head> 
     <body>  
      <div class="someclass"> 
       <h2 class="h3">header 1</h2> 
       <ul class="bulleted"> 
        <li><strong>prop1: </strong>**name**</li> 
        <li><strong>prop2: </strong>**street**</li> 
        <li><strong>prop is 3: </strong>**city**</li> 
        <li><strong>prop 4: </strong>**more**</li> 
       </ul> 
      </div> 
     </body> 
    </html> 
'; 
    $doc = new DOMDocument(); 
    $doc->strictErrorChecking = FALSE; 
    $doc->loadHtml($html); 
    $data = simplexml_import_dom($doc); 
    $properties = $data->xpath('//strong/following-sibling::text()[1]'); 

    var_dump($properties); 

我總是得到的是[強]的內容,而不是[李]內的文本[/ LI]沒有的內容[強]:

array(4) { 
    [0] => 
    class SimpleXMLElement#3 (1) { 
    public $strong => 
    string(7) "prop1: " 
    } 
    [1] => 
    class SimpleXMLElement#4 (1) { 
    public $strong => 
    string(7) "prop2: " 
    } 
    [2] => 
    class SimpleXMLElement#5 (1) { 
    public $strong => 
    string(11) "prop is 3: " 
    } 
    [3] => 
    class SimpleXMLElement#6 (1) { 
    public $strong => 
    string(8) "prop 4: " 
    } 
} 

,如果你點我做我的錯誤我會很高興......

回答

4

不要使用SimpleXML的這個XPath的操作,它在某些方面是有限的,在你的情況下,限制是你不能使用SimpleXML Xpath返回文本節點。 DOMXPath更加強大,它可以返回所有節點類型包括文本節點:

$xpath = new DOMXpath($doc); 
$properties = $xpath->query('//strong/following-sibling::text()[1]'); 

foreach ($properties as $property) 
    var_dump($property->textContent); 

結果:

string(8) "**name**" 
string(10) "**street**" 
string(8) "**city**" 
string(8) "**more**"