Search code examples
phpxpathdomxpath

PHP DOMXPath problem


$xpath = new DOMXpath($doc);
$res = $xpath->query(".//*[@id='post2679883']/tr[2]/td[2]/div[2]");
foreach( $res as $obj ) {
    var_dump($obj->nodeValue);
}

I need to take all the items in the id with the word "post".

Example:

<div id="post2242424">trarata</div>
<div id="post114525">trarata</div>
<div id="post8568686">trarata</div>

Question number two: I need to get this elements with HTML tags, but $obj->nodeValue returns text without html tags.


Solution

  • You could use the xpath function starts-with to filter the nodes in your XPath if all the nodes you want start with "post". For example;

    $xpath->query(".//*[starts-with(@id, 'post')]/tr[2]/td[2]/div[2]");
    

    For the second part, I think has been answered already - PHP DOMDocument stripping HTML tags