tags:

views:

442

answers:

3

So I am working with an API that returns results in XML. Let's just say for argument sake I am returned the following:

<?xml version="1.0" encoding="UTF-8"?>
<Properties>
    <Property>
        <Name>Joes Crab Shack</Name>
        <Address>111 Shack Street</Address>
    </Property>
    <Property>
        <Name>Johns Shoe Store</Name>
        <Address>123 Shoe Avenue</Address>
    </Property>
</Properties>

Now I am using PHP and I get the results into a variable. So essentially this happens:

$xml_results = '<?xml version="1.0" encoding="UTF-8"?><Properties><Property><Name>Joes Crab Shack</Name><Address>111 Shack Street</Address></Property><Property><Name>Johns Shoe Store</Name><Address>123 Shoe Avenue</Address></Property></Properties>';

Now how can I treat this as an XML document and for example loop through it and print out all property names?

+2  A: 

Deserialize into an xml tree, try SimpleXML. That way you can access that data in a more convenient fashion and grab specific xml elements..

driAn
Good answer, but the one with examples was a bit better.
Andrew G. Johnson
A: 

Or you can use inbuilt functions.

Maiku Mori
Couldn't figure out how to use those properly
Andrew G. Johnson
+2  A: 

Something like this should get the job done.

$request_xml = '<?xml version="1.0" encoding="UTF-8"?>
<Properties>
    <Property>
        <Name>Joes Crab Shack</Name>
        <Address>111 Shack Street</Address>
    </Property>
    <Property>
        <Name>Johns Shoe Store</Name>
        <Address>123 Shoe Avenue</Address>
    </Property>
</Properties>';

$xml = simplexml_load_string($request_xml);

$i = 0;
while ($xml->Property[$i])
{   
    echo $xml->Property[$i]->Name;
    echo $xml->Property[$i]->Address;

    $i++;
}
Doug G.
Thanks, the example really helped me
Andrew G. Johnson