سؤال

Let's say my XML is like this:

<?xml version="1.0"?>
<lists>
    <list
        path=".">
        <entry
            kind="dir">
            <name>Assignment1.1</name>
            <commit
                revision="1668">
                <author>netid</author>
                <date>2011-09-07T03:03:58.367692Z</date>
            </commit>
        </entry>
        <entry
            kind="file">
            <name>Assignment1.1/.classpath</name>
            <size>397</size>
            <commit
                revision="1558">
                <author>netid</author>
                <date>2011-09-06T17:00:52.998920Z</date>
            </commit>
      .
      .
      .

    </list>
</lists>

And I store it in a SimpleXML object using

$xml_list = simplexml_load_file(dirname(__FILE__).'/svn_list.xml');

How would I access for example, the revision variable containing 1558?

I can't seem to figure it out using a combination of echo and print_r.

هل كانت مفيدة؟

المحلول

SimpleXML uses a set of classes which implement iterators to work through them, so you can loop through each node using foreach, however the easiest way to navigate the XML once it's loaded is by using SimpleXMLElement::xPath(). To get revision 1558, you can make the following call:

$commit = $xml_list->xpath('//list/entry/commit[@revision="1558"]');

This will return you the nodes underneath <commit revision="1558">, and you can then access them from the $commit variable, which extends ArrayObject.

To get the actual content of the <author> element, you must do the following:

print((string)$commit[0]->author);

SimpleXMLElement instances need to be cast to a type to expose their actual values.

Also, if you want to dump the content of $commit to see its child nodes, the easiest way is to call the asXml() method as follows:

print($commit[0]->asXml());

نصائح أخرى

You are facing difficulties because you have error on your XML file , The </entry> tag was not closed.

You could traverse like this.

<?php
$xml='<lists>
    <list>
        <entry
            kind="dir">
            <name>Assignment1.1</name>
            <commit
                revision="1668">
                <author>netid</author>
                <date>2011-09-07T03:03:58.367692Z</date>
            </commit>
        </entry>
        <entry
            kind="file">
            <name>Assignment1.1/.classpath</name>
            <size>397</size>
            <commit
                revision="1558">
                <author>netid</author>
                <date>2011-09-06T17:00:52.998920Z</date>
            </commit>
            </entry>
    </list>
</lists>';
$xml = simplexml_load_string($xml);
foreach ($xml->list->entry[0]->commit->attributes() as $a=>$v)
{
    echo $v;
}

OUTPUT :

1668
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top