Tutorial :How to echo xml file in php



Question:

How to print an xml file to the screen in php?

This is not working:

$curl = curl_init();          curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);     $result = curl_exec ($curl);     curl_close ($curl);      $xml = simplexml_load_string($result);  echo $xml;  

Is there a simple solution? Maybe without SimpleXML?


Solution:1

You can use HTTP URLs as if they were local files, thanks to PHP's wrappers

You can get the contents from an URL via file_get_contents() and then echo it, or even read it directly using readfile()

$file = file_get_contents('http://example.com/rss');  echo $file;  

or

readfile('http://example.com/rss');  

Don't forget to set the correct MIME type before outputing anything, though.

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


Solution:2

Here's what worked for me:

<pre class="prettyprint linenums">      <code class="language-xml"><?php echo htmlspecialchars(file_get_contents("example.xml"), ENT_QUOTES); ?></code>  </pre>  

Using htmlspecialchars will prevent tags from being displayed as html and won't break anything. Note that I'm using Prettyprint to highlight the code ;)


Solution:3

You can use the asXML method

echo $xml->asXML();  

You can also give it a filename

$xml->asXML('filename.xml');  


Solution:4

Am I oversimplifying this?

$location = "http://rss.news.yahoo.com/rss/topstories";  print file_get_contents($location);  

Some places (like digg.com) won't allow you to access their site without having a user-agent, in which case you would need to set that with ini_set() prior to running the file_get_contents().


Solution:5

If you just want to print the raw XML you don't need Simple XML. I added some error handling and a simple example of how you might want to use SimpleXML.

<?php   $curl = curl_init();          curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);     $result = curl_exec ($curl);       if ($result === false) {      die('Error fetching data: ' . curl_error($curl));     }  curl_close ($curl);        //we can at this point echo the XML if you want  //echo $result;    //parse xml string into SimpleXML objects  $xml = simplexml_load_string($result);    if ($xml === false) {      die('Error parsing XML');     }    //now we can loop through the xml structure  foreach ($xml->channel->item as $item) {      print $item->title;     }  


Solution:6

This worked for me:

echo(header('content-type: text/xml'));  


Solution:7

To display the html/xml "as is" (i.e. all entities and elements), simply escape the characters <, &, and enclose the result with <pre>:

$XML = '<?xml version="1.0" encoding="UTF-8"?>  <root>      <foo>ó</foo>      <bar>&#xF3;</bar>  </root>';    $XML = str_replace('&', '&amp;', $XML);  $XML = str_replace('<', '&lt;', $XML);  echo '<pre>' . $XML . '</pre>';  

Prints:

<?xml version="1.0" encoding="UTF-8"?>  <root>      <foo>ó</foo>      <bar>&#xF3;</bar>  </root>  

Tested on Chrome 45


Solution:8

If anyone is targeting yahoo rss feed may benefit from this snippet

<?php      $rssUrl="http://news.yahoo.com/rss/topstories";      //====================================================      $xml=simplexml_load_file($rssUrl) or die("Error: Cannot create object");      //====================================================      $featureRss =  array_slice(json_decode(json_encode((array) $xml ),  true ), 0 );   /*Just to see what is in it   use this function PrettyPrintArray()   instead of var_dump($featureRss);*/        function PrettyPrintArray($rssData, $level) {      foreach($rssData as $key => $Items) {      for($i = 0; $i < $level; $i++)      echo("&nbsp;");      /*if content more than one*/      if(!is_array($Items)){      //$Items=htmlentities($Items);       $Items=htmlspecialchars($Items);      echo("Item " .$key . " => " . $Items . "<br/><br/>");      }      else       {      echo($key . " => <br/><br/>");      PrettyPrintArray($Items, $level+1);      }      }      }      PrettyPrintArray($featureRss, 0);  ?>  

You may want to run it in your browser first to see what is there and before looping and style it up pretty simple

To grab the first item description

<?php      echo($featureRss['channel']['item'][0]['description']);  ?>  

You can see a demo here


Solution:9

This works:

<?php  $XML = "<?xml version='1.0' encoding='UTF-8'?>  <!-- Your XML -->  ";    header('Content-Type: application/xml; charset=utf-8');  echo ($XML);  ?>  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »