Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output raw XML using php

Tags:

php

xml

I want to output raw xml in a manner similar to http://www.google.com/ig/api?weather=Mountain+View but using PHP.

I have a very simple php script on my webserver:

<?php         $output = "<root><name>sample_name</name></root>";       print ($output); ?>  

All I can see in Chrome/firefox is "sample_name". I want to see:

<root>      <name>sample_name</name> </root> 

I cannot find a tutorial for anything THIS simple.

Thanks

like image 434
RNs_Ghost Avatar asked Aug 21 '11 17:08

RNs_Ghost


People also ask

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 I echo in XML?

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.

Can I use PHP in XML?

If you run the XML file as a PHP script, then yes.


1 Answers

By default PHP sets the Content-Type to text/html, so the browsers are displaying your XML document as an HTML page.

For the browser to treat the document as XML you have to set the content-type:

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

Do this before printing anything in your script.

like image 117
Arnaud Le Blanc Avatar answered Sep 21 '22 04:09

Arnaud Le Blanc