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.y
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(" ");
/*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
You can use the asXML method
echo $xml->asXML();
You can also give it a filename
$xml->asXML('filename.xml');
This worked for me:
echo(header('content-type: text/xml'));
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>ó</bar>
</root>';
$XML = str_replace('&', '&', $XML);
$XML = str_replace('<', '<', $XML);
echo '<pre>' . $XML . '</pre>';
Prints:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<foo>ó</foo>
<bar>ó</bar>
</root>
Tested on Chrome 45