php - XPath query in an XPath query

800

how can a start a second and third XPatch query in an XPatch query?
For example

CodePad = http://codepad.viper-7.com/ZhMNGw

HTML CODE

<div >                
  <h3 >
    <div>
      <a href="/tste/?sd=28726585"> 
        <span > 10:15 </span> 
        <span >THE TITLE<span >some subtitle</span>
        </span>
      </a>
    </div>               
  </h3>
</div> 
<div >                
  <h3 >
    <div>
      <a href="/tste/?sd=287265995"> 
        <span > 10:16 </span> 
        <span >THE TITLE 2<span >some subtitle</span>
        </span>
      </a>
    </div>               
  </h3>
</div> 

PHP

libxml_use_internal_errors(true);
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->strictErrorChecking = false;
$doc->recover = true;
$doc->loadHTMLFile('http://domain.com/startpage.php');
$xpath = new DOMXPath($doc);

$query = "//div[@class='entries']"; // <- QUERY ONE

$entries = $xpath->query($query);
$list = array();

$count = 0;
foreach ($entries as $key => $value)
{        
    $list[$count] = array();

    // get the link <- QUERY TWO
    $list[$count]['url'] =  $xpath->query("//a[@class='selink']");

    // get the title but NOT the subtitle <- QUERY THREE
    $list[$count]['title'] = $xpath->query("//span[@class='titel']");


    $count++;
}


print_r($list);
203

Answer

Solution:

$xpath->query($expr) is executed on the whole document each call within the loop because you don't pass the document node the XPath query should be evaluated in relatively.

With the polymorphic method DOMNodeList query(string $expr, DOMNode $node) you can do a sub query relative to the given $node. This method produces the desired result only if you use a relative XPath $expr (without leading /). To retrieve the string from each DOMNode/TextNode finally use the queries as follows:

$list[$count]['url'] = $xpath->query("h3/div/a[@class='selink']/@href", $value)->item(0)->value;
$list[$count]['title'] = $xpath->query("h3/div/a/span[@class='titel']/text()", $value)->item(0)->wholeText;

I edited your CodePad code here.

regards, Max

People are also looking for solutions to the problem: php - How to edit selected file in a dropdown list in textarea and then save it?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.