xpath problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kc11
Forum Commoner
Posts: 73
Joined: Mon Sep 27, 2010 3:26 pm

xpath problem

Post 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
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: xpath problem

Post 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>
kc11
Forum Commoner
Posts: 73
Joined: Mon Sep 27, 2010 3:26 pm

Re: xpath problem

Post 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
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: xpath problem

Post 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.
Post Reply