'Output raw XML using php
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
Solution 1:[1]
<?php
header('Content-Type: application/xml');
$output = "<root><name>sample_name</name></root>";
print ($output);
?>
Solution 2:[2]
You only see "sample_name" because you didn't specify that your output is XML and the browser thinks it's HTML so your XML-Elements are interpreted as HTML-Elements.
To see the raw XML, you need to tell the browser that you're actually sending XML by sending the correct content-type in the HTTP header:
header('Content-Type: application/xml');
This needs to be send (put in the code) before you put out anything else.
Solution 3:[3]
For completeness sake, as nobody's mentioned it yet, you can also output raw XML within an HTML page, by escaping < as <, > as >, and & as &. To do that, use the awkwardly named htmlspecialchars function.
Often, you'll also want to preserve whitespace in the argument, which can be done by surrounding it in <pre> tags. So a common line for debugging or including a sample is this:
echo '<pre>' . htmlspecialchars($raw_xml) . '</pre>';
Solution 4:[4]
Just press Ctrl+U (Control+U), Your browser will display the page's raw source code under a new Tab, be it XML or HTML or whatever else...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | IMSoP |
| Solution 4 | NabilJaran |
