0

I've seen this problem a few times, and would like a definitive answer.

Given this structure in xml:

<ByteListSet>
    <Byte Order="0">14</Byte>
</ByteListSet>

I am not able to access the attribute 'order'. var_dump (unsurprisingly) does not show any attributes for ByteListSet. Indeed, foreach iteration does not produce a @attributes item.

However, the following structure:

<ByteListSet>
    <Byte Order="0"><Value>3729</Value></Byte>
</ByteListSet>

Results properly in ByteListSet having a child Byte that is a SimpleXmlObject which has @attributes.

I would assume that SimpleXML is indeed picking up the @attributes from the first case, but where is it keeping them? The trouble is that in the former structure, ByteListSet produces this on var_dump of ->children():

object(SimpleXMLElement)[25]
  public 'Byte' => string '14' (length=2)

if I get_object_vars() on it and var_dump each, I simply get:

string '14' (length=2)

Indicating that Byte is not being returned to me as an xml object, but just as a string; as a property of the ByteList object above it.

Order="0" is there somewhere, but I don't have access to it. How do I get to it? NOTE: ->attributes() returns, as you would expect, a blank array.

(We do not control this schema, so it can't be restructured.)

Deduplicator
  • 44,692
  • 7
  • 66
  • 118

1 Answers1

0

You wrote:

Given this structure in xml:

<ByteListSet>
    <Byte Order="0">14</Byte>
</ByteListSet>

I am not able to access the attribute 'order'.

Sure, because the attribute order does not exist. XML is case-sensitive, the attribute is named Order with uppercase O at the beginning.

Using the right attribute name allows you to access the value as outline in Example #5 in the basic examples of the SimpleXML extension you can find in the manual:

$ByteListSet = simplexml_load_string(<<<XML
<ByteListSet>
    <Byte Order="0">14</Byte>
</ByteListSet>
XML
);

echo $ByteListSet->Byte['Order']; # 0

Please keep in mind that what you see in var_dump or print_r is not always what you get. This is espeically true for Simplexml (compare: How to get values of xml elements?; SimpleXML and print_r() - why is this empty?), however, also for other objects in PHP that make use of ArrayAccess, __toString() or IteratorIterator / IteratorAggregate.

Please let me know if that answers your question. You were not very specific which existing solutions you have not understood so far, so I answered your question, but I'm not 100% if I hit the nail.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836