Andrew G. Johnson
Andrew G. Johnson

Reputation: 27003

Have XML results in plaintext, want to loop through them in PHP

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?

Upvotes: 1

Views: 1422

Answers (2)

Doug G.
Doug G.

Reputation: 56

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++;
}

Upvotes: 4

driAn
driAn

Reputation: 3335

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

Upvotes: 2

Related Questions