php simple xml element question/bug - php

I have some xml, lets say <names number="12"></names>
When I run the following:
$simpleXMLElement = new SimpleXMLElement($xml);
pr($simpleXMLElement);
I get the following:
SimpleXMLElement Object
(
[#attributes] => Array
(
[number] => 12
)
[0] =>
)
It throws in that 0 entry. This is weird. I don't know what it's supposed to represent. If I do this instead:
<names number="12"><name first="oliver" /></names>
I get the following output:
SimpleXMLElement Object
(
[#attributes] => Array
(
[number] => 12
)
[name] => SimpleXMLElement Object
(
[#attributes] => Array
(
[first] => oliver
)
)
)
This is as expected (for me at least). Any thoughts/direction?

First: if you don't correctly format your post, the XML will not be displayed. Indent any code with at least 4 spaces.
Secondly, do not expect print_r() or var_dump() to give you an exact representation of a SimpleXMLElement because SimpleXML uses lots of magic, so children and attributes won't necessarily show up in the output.

It seems to be just SimpleXML doing a quick-and-dirty job of parsing the element: Since you have <names></names>, it adds an array inside the element, as expecting elements within it, and when it doesn't find any elements inside the names tags, it leaves an empty array, with the key 0, since it doesn't know what name to give it.
A short tag (<names />) shouldn't generate the empty content. (As weird as that sounds.)

Related

Not able to access attributes in xml

Am trying to access the attribute of the simple xml
SimpleXMLElement Object
(
[#attributes] => Array
(
[Index] => 21
)
[Data] => Hello world
)
i want to access Index attribute. I tried the following code but its not
working for me
$xml->attributes()->Index
There you go my friend:
$xml->attributes()['Index']
Sometimes I noticed I had to cast the result when it's a string. Like:
(string)$xml->attributes()['Index']

Parsing a timestamp based PHP std class obkect

I have a PHP standard class object converted from json_decode of a REST call on an API which looks like :
Array
(
[1437688713] => stdClass Object
(
[handle] => Keep it logically awesome.
[id] => 377748
[ping] => stdClass Object
(
[url] => https://api.me.com
[id] => 377748
[name] => web
[active] => 1
[events] => Array
(
[0] => data_new
[1] => data_old
)
So far i had no issues in parsing any of the PHP objects. However this one is failing because i can not access the nested object elements using a key since 1437688713 is not assigned to a key and accessing an object is failing if i try to do this:
$object->1437688713->handle
Is there a way to access these elements ?
Update: one more thing, i would never know this value (1437688713) in advance. Just like a key. All i get is a stdclass object which i have to parse.
The outer part of your data is an array, not an object. Try:
$array['1437688713']->handle;
or if you don't know the key, you can iterate over the array (handy if it may contain multiple objects too):
foreach ($array as $key => $object) {
echo $key; // outputs: 1437688713
echo $object->handle; // outputs: Keep it logically awesome.
}
Get the first item from $object array
$first_key = key($object);
Use it with your response array,
$object[$first_key]->handle;
Or, the first element of array
$first_pair = reset($object)->handle;

Explanation for traversing object variables of simplexml node list

I have this
$xml = new SimpleXMLElement($output);
$names = $xml->param->value->array->data;
Here is the output
SimpleXMLElement Object
(
[value] => Array
(
[0] => SimpleXMLElement Object
(
[struct] => SimpleXMLElement Object
(
[member] => SimpleXMLElement Object
(
[name] => school
[value] => SimpleXMLElement Object
(
[struct] => SimpleXMLElement Object
(
[member] => Array
(
[0] => SimpleXMLElement Object
(
[name] => schoolid
[value] => SimpleXMLElement Object
(
[string] => 49961
)
)
[1] => SimpleXMLElement Object
(
[name] => schoolname
[value] => SimpleXMLElement Object
(
[string] => Millersville Elementary School
)
)
I am trying to get to the "schoolname" value
using
for($i=0;$i<count($names);$i++) {
echo $names[0][$i]->struct->member->value->struct->member[0]->value.'<br>';
}
I've also tried as string($names[0]etc.) with no success. I think I am messing up the order in the beginning with $names[0][$i]??
Any help is much appreciated!
Consider learning XPath if you feel lazy. It's the easy way to address your issue if you don't want to loose it with a never ending streak of ->'s :)
Learning XPath is also an investment. When you deal with XML you need to know it. It's the SQL of XML or DOM (see DOMXPath).
I know this is not really an answer but spending some time and what I pointed out here is worth it and will also solve you problem.
Here is the solution using xpath to get fieldname and values
$cols = $xml->xpath('//member/value/struct/member/name');
$names = $xml->xpath('//member/value/struct/member/value/*');
for($i=0;$i<count($cols);$i++) {
echo $cols[$i].' = '.$names[$i].'<br>';
}
xpath is a must for anyone dealing with xml!
The result $name is a mix of valuse (object and array).
Try to convert $name to an object only or an array only.
The example you posted is not complete, could not try to chaqge it.
I recently had a similar issue, I ended up writing something that flattened the whole structure to be arrays within arrays, much more travesrsable, but to the matter at hand, I often find it helpful to var_dump/print_r each stage and build it up level by level.
$names is an object so it would seem to me the reference you want is:
$names->value[0]->struct->member->value->struct->member['value'][1]->value;
Edit: I've ignored the looping part for now as I think you'll need to re-evaluate your count(), it seems it needs to be count($names->value), which is the array of schools if I'm correct, in which case the $i would go in the first [0].

Sort multidimensional XML with PHP by date

I can't find an exact duplicate of this question, as my nodes are numerical keys.
I need to sort this xml by date - newest first:
[article] => Array
(
[0] => SimpleXMLElement Object
(
[value] => some value
[date] => 2012-08-13 18:54:09
)
[1] => SimpleXMLElement Object
(
[id] => some more value
[date] => 2012-08-09 10:24:06
)
[2] => SimpleXMLElement Object
(
[id] => another value
[date] => 2012-08-11 20:45:44
)
)
How can I best do that - possibly WITHOUT turning the XML into a PHP array and sorting it then.
From your sample, it looks like you have an array of objects already, so usort would work fine.
The callback would look something like this:
function compare_node_dates($a, $b)
{
return
strtotime((string)$b->date)
-
strtotime((string)$a->date);
}
However, if your outermost variable isn't actually an array, there is no way I'm aware of doing this without creating an array, sorting that, and using that to construct brand new XML.

Accessing certain properties of a SimpleXMLElement Object

When I print_r() the SimpleXMLElement Object referenced by variable $xmlObject, I see the following structure:
SimpleXMLElement Object
(
[#attributes] => Array
(
[uri] => /example
)
[result] => SimpleXMLElement Object
(
[message] => Record(s) added successfully
[recorddetail] => Array
(
[0] => SimpleXMLElement Object
...
)
)
)
Notice how the $xmlObject->result->message property looks like it is just a string. However, if I do print_r($xmlObject->result->message), I get the following:
SimpleXMLElement Object
(
[0] => Record(s) added successfully
)
So at this point I'm confused. Why is $xmlObject->result->message being identified as an instance of SimpleXMLElement Object in this case, when the result of printing the full $xmlObject doesn't suggest this?
And how do I actually access this value? I've tried $xmlObject->result->message[0], but it just prints out the same thing (i.e. the last code snippet I posted).
The representation you get when using print_r or var_dump on a SimpleXMLElement has very little to do with how it is structured internally. For instance there is no property #attributes you could access with $element['#attributes']['uri'] either. You just do $element['uri']
This is simply the way it is. SimpleXmlElement objects behave different. Make sure you read the examples in the PHP Manual before using SimpleXml:
http://php.net/manual/en/simplexml.examples-basic.php
To understand the implementation it in detail, you'd have to look at the source code:
http://lxr.php.net/opengrok/xref/PHP_TRUNK/ext/simplexml/simplexml.c
To print $xmlObject->result->message you just do echo $xmlObject->result->message. That will autocast the SimpleXmlElement to string.

Categories