tags:

views:

98

answers:

3

I am making an API call that should return something like the following,

 <?xml version="1.0" encoding="utf-8" ?> 
    <Chart:chart xmlns:Chart="http://www.zillow.com/vstatic/3/static/xsd/Chart.xsd"&gt;
    <request>
    <zpid>48749425</zpid> 
    <unit-type>percent</unit-type> 
    <width>300</width> 
    <height>150</height> 
    </request>
    <message>
    <text>Request successfully processed</text> 
    <code>0</code> 
    </message>
    <response>
    <url>http://www.zillow.com/app?chartDuration=1year&amp;chartType=partner&amp;height=150&amp;      page=webservice%2FGetChart&service=chart&showPercent=true&width=300&zpid=48749425</url> 
    </response>
    </Chart:chart>

And what I need is to display the chart image that is at the returned URL, but how do I do that?!?
Thank you!

A: 

Given the XML data in a variable $xml, you could parse it and output an <img> tag using XMLDOM functions:

$doc = new DOMDocument();
$doc->loadXML($xml);


$nodes = $doc->getElementsByTagName("url");
if ($nodes->length>0)
{
    $node=$nodes->item(0);
    $url=htmlentities($node->nodeValue);

    echo "<img src=\"$url\">";
}

You could also use XPath

$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);

$nodes = $xpath->evaluate('Chart/response/url');
if ($nodes->length>0)
{
    $node=$nodes->item(0);
    $url=htmlentities($node->nodeValue);

    echo "<img src=\"$url\">";
}

There is also simplexml too

$doc = simplexml_load_string($xml);
$url = htmlentities($doc->response->url);
echo "<img src=\"$url\">";

Note that the XML you posted is invalid - the & characters in the URL should be &amp; for any of these XMLDOM methods to work properly. But this at least illustrates how to work with XML "properly"

So, a simpler approach would be to just rip out the url with a regex

if (preg_match('{<url>(.*?)</url>}', $xml, $matches))
{
     $url=htmlentities($matches[1]);
     echo "<img src=\"$url\">";
}
Paul Dixon
Awesome thanks guys. The XML I posted I copied from their API example output... I am brand new to XML obviously, :)Question though, where you both are using $xml up there, does that mean the API call?
thatryan
+1  A: 

You could use simple_xml:

$x = simplxml_load_string($xml);
echo '<img src="' . htmlspecialchars($x->response->url) . '">';
Greg
Hey Greg, thanks for responding. Could not get that to work with load_string, but I removed the htmlspecialchars() and changed to load_file and it worked. Can you tell me why? :)THanks again.
thatryan
A: 

Thank you guys for getting me going the right way. I am not sure why I could not get it to work with the load_string function..?

This is what I used and it worked, do you know why?

<?php
$xml = 'http://www.zillow.com/webservice/GetChart.htm?zws-id=******&amp;unit-type=percent&amp;
zpid='.$title->zpid.'&width=300&height=150';
$chart = simplexml_load_file($xml);
echo '<img src="' .$x->chart->url . '">';
?>
thatryan