1

I'm using simplexml_load_string to load some XML:

$xml = "<payment><cardHolderName><![CDATA[John Smith]]></cardHolderName></payment>";
$xml = simplexml_load_string($xml, null, LIBXML_NOCDATA);

How can I then access the cardHolderName (John Smith) using xpath? I've tried:

$name = $xml->xpath('/payment/cardHolderName');
echo $name;

But the value is empty and I get a warning:

Array to string conversion

Same result with all of these xpaths:

'/payment/cardHolderName'
'/payment/cardHolderName[1]'
'/payment/cardHolderName/text()'
'/payment/cardHolderName[1]/text()'

Thanks in advance.

4
  • What's the code that gives you this warning? Commented Feb 26, 2013 at 10:45
  • @fab I've updated my question to include the code. Commented Feb 26, 2013 at 10:47
  • 1
    The xpath() method always returns an array with alll matched nodes. You can't use an xpath with it that returns anything else than nodes. Commented Feb 26, 2013 at 10:52
  • Just FYI: SimpleXMLElement::xpath() has no support for the xpath function text(). You can only query elements and attributes with simplexml xpath. Commented Mar 15, 2013 at 19:22

2 Answers 2

2

see if this works for you:

$name = $order->xpath('/payment/cardHolderName');
echo $name[0];
Sign up to request clarification or add additional context in comments.

1 Comment

It does, thank you. I should've mentioned that I'd already worked that out, but I wondered why it won't work with xpath alone.
0

The XPath query isn't quite right, in this context $xml represents your root element ("payment") so you would refer to the name with

$order->xpath('cardHolderName');

That said, AFAIK simplexml has less than stellar XPath support. You 'd be doing this much easier with DOMDocument and DOMXPath instead, which works as you 'd expect.

1 Comment

Sorry, that was in fact a typo when transferring the code. I still get the same result, so I'll look into DOMDocument and DOMXpath.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.