tags:

views:

35

answers:

2

Hello,

I have an xml file that has attributes/tags for mutliple levels in the feed however simplexml isn't showing them in the print_r dump.

Example:

<types tag1="1287368759" tag2="1287368759">
    <locations>
        <segment prefix="http" lastchecked="0">www.google.com</segment>
        <segment prefix="http" lastchecked="0">www.google.com</segment>
        <segment prefix="http" lastchecked="0">www.google.com</segment>
        <segment prefix="http" lastchecked="0">www.google.com</segment>
        <segment prefix="http" lastchecked="0">www.google.com</segment>
    </locations>
</types>

Problem is the tags in the <types> works fine and shows up in the xml dump, however the tags in each of the segments are not there. Any help?

A: 

SimpleXML will not show the attributes if the element has normal data in it, you need to use as the example below:

<?php
$xml = '<types tag1="1287368759" tag2="1287368759">
    <locations>
        <segment prefix="http" lastchecked="0"><![CDATA[www.google.com]]></segment>
        <segment prefix="http" lastchecked="0"><![CDATA[www.google.com]]></segment>
        <segment prefix="http" lastchecked="0"><![CDATA[www.google.com]]></segment>
        <segment prefix="http" lastchecked="0"><![CDATA[www.google.com]]></segment>
        <segment prefix="http" lastchecked="0"><![CDATA[www.google.com]]></segment>
    </locations>
</types>';

$xml_data = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

print_r($xml_data);

foreach ($xml_data->locations->segment as $segment) {
    print $segment['prefix'] . ' - ' . ((string) $segment) . "\n";
}

I'm not sure why this is, but I found that that works,

Hope it helps.

NiGhTHawK
that works however the problem is I need to get the prefix/lastchecked tag values as well, these don't show up in the print_r dump
Joe
I updated the example to include the displaying of an attribute, but as Wrikken stated in his comment there are other ways to do this...
NiGhTHawK
With regards to the attributes you can also look here: http://stackoverflow.com/questions/1652128/accessing-attribute-from-simplexml
NiGhTHawK
many thanks, strange how a print_r didn't reveal all the array levels, however they were all there!
Joe
+1  A: 

SimpleXML is more like a resource, so var_dumping / print_ring will not yield any usable results.

A simple foreach($xml->types->segment->locations as $location) should work to loop through your locations, and use getAttributes() to get attributes of a node.

I'd suggest taking a closer look at the examples & functions in the manual (look at the comments too), as working with SimpleXML may be simple after you know how, you do need some background on how to use it as the usual introspection is not possible.

Wrikken
the getattributes() helped, thanks!
Joe