2

I am trying to read an attribute value of the root node of an XML fed into the simplexml_load_string() method in PHP.

Here is an example,

<data status="Active">
 <user> <userid> 1 </userid> </user>
 <user> <userid> 2 </userid> </user>
<data>

I am trying to read the value of 'status' in the above XML string:

echo $xml->user[0]->userid;
echo $xml->attributes()->status

The statements don't work too, var_dump() outputs "NULL".

5 Answers 5

4

echo (string)$userNode->attributes()->status should work

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

2 Comments

Is the explicit cast necessary with echo or is it merely "good style"?
@Tomalak - in the simplexml implementations ive messed with, I had to explicitly do it or it'd try to echo the object reference out. perhaps in newer implementations you don't have to do it since the toString method automatically does it?
2

Besides the attributes() method you can simply access the element's attributes by treating the element object like an array (SimpleXMLElement implements ArrayAccess)

$xml = simplexml_load_string('<user status="Active"></user>');
echo 'status=', $xml['status'];

But to access attributes in other namespaces you have to use attributes() (afaik).

Comments

0
$xml = simplexml_load_string('<user status="Active"></user>');

echo $xml->attributes()->status;

Comments

0

Thanks for the replies... Parsing was not really the problem.

I missed the following cURL parameters,

curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");

I was treating a boolean value (cURL response) as an XML file :)

Thanks all...

Comments

0

Sorry but in your example XML you did not close your end <data> tag.

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.