Reputation: 183
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!
Upvotes: 0
Views: 714
Reputation: 183
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!
Upvotes: 1
Reputation: 3065
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]
.
Upvotes: 0
Reputation: 443
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.
Upvotes: 0
Reputation: 12985
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.
Upvotes: 6