Search code examples
phpxml

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?


Solution

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