0

I have an XML string like this in a PHP variable. This string is generated through a REST request to a service using nusoap in PHP

<exception name="xyz.TestException" message="Invalid Username.jake"/>

How do I use PHP to retrieve the XML string attributes in an array, so I can use them for messaging purposes?

Ex: The result PHP array should look like this.
$attrArray = array();
$attrArray["name"]= "xyz.TestException" 
$attrArray["message"] = "Invalid Username.jake"

Thanks,

2
  • 1
    Use SimpleXML. See the 5th example. Commented Sep 6, 2012 at 18:22
  • Are you getting the complete XML (with <?xml version...?> header) or just a part of it? Commented Sep 6, 2012 at 18:22

1 Answer 1

1

You can do it like this, not very clean:

    $string = '<exception name="xyz.TestException" message="Invalid Username.jake"/>';

    $parser = new SimpleXMLElement($string);
    $attrs  = array();
    // Convert attributes to string
    foreach($parser->attributes() as $key => $value)
            $attrs[$key] = "$value"; // Object to string conversion using quotes

    print_r($attrs);

You can also directly and more cleanly access $parser["name"] and $parser["message"].

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

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.