0

How can I echo in PHP the OK attribute in this SimpleXMLElement?

I've been trying to figure this one out for hours but I can't solve it.

SimpleXMLElement Object(
    [@attributes] => Array(
        [OK] => No
    )
    [NEWS] => SimpleXMLElement Object(
        [NEWS] => Blocked
    )
)
Tomiapi
  • 5
  • 1
  • 2

3 Answers3

2

If you look closely at the manual, you'll see that there is an attributes() function.

As long as you don't have any custom namespaces, you can simply call your XML object by attributes, then call the certain attribute by it's name.

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

Should return No.

Dave Chen
  • 10,887
  • 8
  • 39
  • 67
1

I'm not sure if you're tripping up on the output of print_r, but the underlying XML for that example would be something like <foo OK="No"><NEWS>Blocked</NEWS></foo>, so OK is an ordinary XML attribute.

As the manual's basic usage examples show, the simplest way to access an attribute with SimpleXML is using ['attribute_name']. So in your case, it will be like this:

echo $node['OK'];

Note that like all accessors, that returns another SimpleXML object, not a string, so if you're passing it around to other parts of your code, you should cast it to a string with the syntax (string) to avoid tripping up other code:

$ok_value = (string)$node['OK'];

As others have pointed out, there's also an attributes() method, which lets you loop through all attributes of a node, or access attributes which are in a particular XML namespace. These two lines are equivalent to the two above:

echo $node->attributes()->OK;
$ok_value = (string)$node->attributes()->OK;
IMSoP
  • 89,526
  • 13
  • 117
  • 169
0
 $result = [PUT OBJECT HERE]->attributes()->OK;
  echo $result;
vjpaleo
  • 1
  • 1