Page 1 of 1

xpath problem

Posted: Wed Dec 14, 2011 11:06 pm
by kc11
Hi everyone,

I am having trouble getting the next sibling in xpath ( I'm using simplexml ) .

The HTML looks like this:

[text]
<div id="body">
---------
---------
</div>
text string1
<br>
<br>
[/text]

So far I have:

Code: Select all


$postid=$simplexml->xpath("//div[@id='body']"); 

Can anyone modify this to get text string1?

Thank you,

KC

Re: xpath problem

Posted: Thu Dec 15, 2011 9:31 am
by Weirdan
with DOM the following would work:

Code: Select all

<?php
   $html = '<?xml version="1.0"?>
    <root>
    blah
    <div id="body">
    ---------
    ---------
    </div>
    text string1
    <br/>
    grgr
    <br/>
    </root>
    ';
    
    $x = simplexml_load_string($html);
    $xml = dom_import_simplexml($x);
    $xpath = new DOMXPath($xml->ownerDocument);
    foreach ($xpath->evaluate("//div[@id='body']/following-sibling::text()[1]") as $elt) {
        var_dump($elt->wholeText);
    }
Doesn't seem to work with simplexml though. Overall this doesn't seem to be a standard-compliant way as the primary node type for the following-sibling axis is element, not any node and thus in theory it should have returned <br>

Re: xpath problem

Posted: Thu Dec 15, 2011 1:30 pm
by kc11
Thank you Weirdan,

That works! Do you have any online xpath references you can recommend? I wasn't able to find much on how to do more complex xpath requests in php.

Best regards,

KC

Re: xpath problem

Posted: Fri Dec 16, 2011 4:32 am
by Weirdan
kc11 wrote:Do you have any online xpath references you can recommend?
For me it's Google, mostly, plus some field experience with xpath. The spec on w3.org is also pretty usable if you know what to look for. Previously I used Xpather extension for firefox in my experiments with xpath.