Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo XML file in PHP

Tags:

php

xml

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?

like image 391
chris Avatar asked Jul 29 '09 11:07

chris


People also ask

How do I echo an XML file?

The contents from a URL can be fetched through the file_get_contents() and it can be echoed. or read using the readfile function. readfile('http://example.com/'); header('Content-type: text/xml'); //The correct MIME type has to be set before displaying the output. echo $xml->asXML(); or $xml->asXML('filename.

HOW include XML file in PHP?

$dom2 = new DOMDocument; $dom2->load('existingFile. xml'); $dom2->documentElement->appendChild($dom2->importNode($fragment, true)); This would append the fragment as the last child of the root node.

How display XML file in browser using PHP?

php header("Content-type: text/xml"); $yourFile = "xmlfile. xml"; $file = file_get_contents($yourFile); echo $file; If you insist on simple xml you can write like this.

How do you read and write XML document with PHP?

Start with $videos = simplexml_load_file('videos. xml'); You can modify video object as described in SimpleXMLElement documentation, and then write it back to XML file using file_put_contents('videos. xml', $videos->asXML()); Don't worry, SimpleXMLElement is in each PHP by default.


1 Answers

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'); 
like image 88
Josh Davis Avatar answered Sep 20 '22 21:09

Josh Davis