Wednesday, June 18, 2008
Access external XML files in Silverlight using PHP
This is written for Silverlight v2 beta 2.

Silverlight only allows you to use Relative paths when loading XML files. That means the XML file has to be on your server. In this tutorial I will show you how to access an Absolute path or an external XML file.

In order to do this we will need to write an XML proxy page in PHP. Our PHP page will need to take the XML contents from an external XML page and render it as its own. Then your Silverlight application can simply connect that our XML proxy page for its data.

If you would like to know how to load the XML into an XmlReader you can read my previous entry Using XmlReader in Silverlight.

If we wanted to be slick, we can take in the XML path dynamically through the query string so we can reuse our XML proxy page in other Silverlight applications that require access to external XML files. Luckily this is very easy to do in PHP. Just copy this code into a file called xml_proxy.php.

<?php
header('Content-type: text/xml');

if (isset($_GET['XML']))
   echo(file_get_contents($_GET['XML']));
else
   echo('<Data>No Input Entered</Data>');
?>


*note* Some hosts do not support file-access, like mine. However, I was able to get around this by using the following code.

<?php
header('Content-type: text/xml');

if (isset($_GET['XML']))
{
   $c = curl_init();
   curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($c, CURLOPT_URL, $_GET['XML']);
   $contents = curl_exec($c);
   curl_close($c);

   if (!$contents)
      $contents = '<Error>Could not load file</Error>';

   echo($contents);
}
else
   echo('<Data>No Input Entered</Data>');
?>


Here is an example of my xml proxy page. http://silverlight.whatisreal.com/xml_proxy.php?XML=http://rss.slashdot.org/Slashdot/slashdot.

In your Silverlight application change the Uri path to the example from above.

Uri url = new Uri("xml_proxy.php?XML=http://rss.slashdot.org/Slashdot/slashdot", UriKind.Relative)


That is all there is to it.

0 Comments: