0

Possible Duplicate:
PHP get values from SimpleXMLElement array

I am using simplexml_load_string() to parse xml string. It reads the input correctly, but doesn't return any data only blank nodes.

My xml data is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<leads>
    <auth>
        <username>user</username>
        <password>user</password>
    </auth>
</leads>

And the function is:

$xmlObj = simplexml_load_string($xml);

    if ($xmlObj) {
        echo "Failed loading XML\n";
        foreach(libxml_get_errors() as $error) {
            echo "\t", $error->message;
        }
    } 
    else{
        print_r($xmlObj);
     }

When I am trying to print the result I am getting a blank nodes like

<auth>
    </username>
    </password>
</auth>
Community
  • 1
  • 1
Sreehari
  • 515
  • 3
  • 11
  • 27
  • Your question might become more clear if you actually provide the code so it is clear how you use the function in question. Also you have not given any information what your expected output would be, so your question can be easily misread in the sense that the output you provide would be the original document. – hakre Dec 25 '12 at 16:23
  • Where is the original XML string? I ask because after you've updated your question it might be that there is an issue with it. Can you provide some sample? Or are you using that sample verbatim? Because with that data it works for me: http://eval.in/5334 - **Take care:** You have to check string-loading success this way, otherwise you run into a problem: `if (false === $xmlObj) {` - maybe that is your issue? – hakre Dec 25 '12 at 16:43
  • I am getting the xml above sample xml as webservice response, and I am trying to parse this response – Sreehari Dec 25 '12 at 17:09
  • All I can say for the data you have got provided this works. You might want to share more of your code because with the information that you have to provided it is not clear what your actual issue is. Which makes your question useless because it is not clear what you ask about. you might want to provide [a hexdump of your XML string](http://stackoverflow.com/questions/1057572/how-can-i-get-a-hex-dump-of-a-string-in-php). – hakre Dec 25 '12 at 18:01

2 Answers2

2

I got the solution

$username = (string) $xmlObj->auth->username;

I just put "(string)"

Sreehari
  • 515
  • 3
  • 11
  • 27
0

You need to use the SimpleXMLElement::asXML() methodDocs to get the XML back, otherwise it would return the value of the root node which is empty, hence the empty string.

So it's all fine and dandy.

Additionally and as a pre-caution, do the proper return value checking:

$obj = simplexml_load_string($xml)
if ($obj === FALSE) {
    throw new Exception('Failed to load XML string.');
}

I hope this is helpful and sheds some light into your issue.

hakre
  • 193,403
  • 52
  • 435
  • 836