开发者

php - simplexml issue

I have an xml file that has attributes/tags for mutliple levels in the feed however simplex开发者_如何学Cml 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜