2

I want to get the value '23452345235' of the parameter with name="userID" from this :

<?xml version="1.0" encoding="UTF-8"?>
    <callout>
        <parameter name="UserID">
            23452345235
        </parameter>

        <parameter name="AccountID">
            57674567567
        </parameter>

        <parameter name="NewUserID">
            54745674566
        </parameter>

     </callout>

I'm using this code:

$xml = simplexml_load_string($data);
$myDataObject = $xml->xpath('//parameter[@name="UserID"]');
var_dump($myDataObject);

And I'm getting this:

array(1) {
[0] =>
    class SimpleXMLElement#174 (1) {
        public $@attributes =>
        array(1) {
          'name' =>
          string(6) "UserID"
        }
    }
}

I actually want to get the value of '23452345235' or receive the parameter in order to get this value.

What I'm doing wrong?

1
  • You're overlooking that you have it already, it's the first (and only) value in the array: var_dump(trim($myDataObject[0])); - outputs: string(11) "23452345235". Commented Oct 12, 2014 at 21:16

2 Answers 2

3

Well you can (optionally) put it under a loop. Like this:

$myDataObject = $xml->xpath('//parameter[@name="UserID"]');
foreach($myDataObject as $element) {
    echo $element;
}

Or directly:

echo $myDataObject[0];

Actually is quite straightforward, as seen on your var_dump(), its an array, so access it as such.

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

Comments

1

SimpleXMLElement::xpath() can only return an array of SimpleXMLElement objects, so it generates an element and attaches the fetched attribute to it.

DOMXpath::evaluate() can return scalar values from Xpath expressions:

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

var_dump($xpath->evaluate('normalize-space(//parameter[@name="UserID"])'));

Output:

string(11) "23452345235"

Comments

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.