1

I am trying to perform a simple xpath lookup using an XML file from an HTTP POST. I've been pulling my hair out, as this should work!! Everything I've found thus far is a result of the namespace, but I have no namespace in this XML.

<?xml version="1.0" encoding="UTF-8"?> <foo> <bar> <name>Frank</name> </bar> </foo> 

Here is the simple code I'm using.

$xml = new SimpleXMLElement(file_get_contents("php://input"); print_r($xml->xpath("//FOO/bar/name")); 

This gives me an empty array!

Array ( [0] => SimpleXMLElement Object ( ) ) 

If I just do print_r($xml->xpath("//foo")); I see it has the data, but as soon as I try to get the value of name, I get nothing. :(

Array ( [0] => SimpleXMLElement Object ( [bar] => SimpleXMLElement Object ( [name] => Frank ) ) ) 

What is the deal?? Thank you!!

5
  • FOO !== foo. Thought I was cleaning up code with edit. CaSe sensitivity was actually your issue. Suggest close as a 'typo' question. stackoverflow.com/posts/49436522/revisions Commented Mar 22, 2018 at 19:05
  • 1
    Looks like it's broken prior to 5.6.10: 3v4l.org/sZX7P Commented Mar 22, 2018 at 19:06
  • If you really just want the value, you can do $xml->xpath("//foo/bar/name")[0]->__toString() as far back as 5.4. That doesn't address the underlying issue of what you're trying to do for your current version though. Commented Mar 22, 2018 at 19:16
  • Some point in 5.5 behaviour changed. At 5.5.31 it started working again, like it did back in 5.4. So exact behaviour will depend on version. Commented Mar 22, 2018 at 20:19
  • I'm using 5.4.16 which is in the broken list. Thanks Alex. Patrick, thank you as well - that's similar to the posted answer. Hate to be "weird" like that, but it's the version I'm using it seems. Commented Mar 22, 2018 at 20:44

1 Answer 1

1

This gives me an empty array!

No it doesn't. Look closely at your output, and you will see that you have an array with one result in it, which is a SimpleXMLElement object.

Unfortunately, print_r doesn't handle SimpleXMLElement objects very well, and in some versions of PHP works better than others, so it doesn't accurately show you what SimpleXMLElement you have.

But your production code won't be relying on print_r, it will be relying on the actual content of that element, so let's see if we can get the content:

// Text content of an element is (string)$element var_dump( (string)$first_result ); # string(5) "Frank" // Render element back to XML var_dump( $first_result->asXML() ); # string(18) "<name>Frank</name>" 

This gives the right output in all versions of PHP on 3v4l.org. So there isn't actually a problem at all! :)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.