[php] How to echo xml file in php

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?

This question is related to php xml

The answer is


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


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().


This worked for me:

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

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


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

You can use the asXML method

echo $xml->asXML();

You can also give it a filename

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

The best solution is to add to your apache .htaccess file the following line after RewriteEngine On

RewriteRule ^sitemap\.xml$ sitemap.php [L]

and then simply having a file sitemap.php in your root folder that would be normally accessible via http://www.yoursite.com/sitemap.xml, the default URL where all search engines will firstly search.

The file sitemap.php shall start with

<?php
//Saturday, 11 January 2020 @kevin

header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

<url>
  <loc>https://www.yoursite.com/</loc>
  <lastmod>2020-01-08T13:06:14+00:00</lastmod>
  <priority>1.00</priority>
</url>


</urlset>

it works :)


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 ;)


This works:

<?php
$XML = "<?xml version='1.0' encoding='UTF-8'?>
<!-- Your XML -->
";

header('Content-Type: application/xml; charset=utf-8');
echo ($XML);
?>