Unable to export XML from PHP using WAMPServer
I am using WAMPServer 2.1 on my local machine. I am trying to create a simple PHP script to output an XML file. I cannot get it to work without generating an error on IE and Chrome. On Firefox 4, it works.
Here is the PHP:
<?php
main();
function main()
{
header("Content-type: application/xml");
OutputXML('xml/login_user_good.xml');
exit(0);
}
function OutputXML($filename)
{
echo file_get_contents($filename);
}
?>
Here is the XML file:
<?xml version="1.0" encoding="utf-8" ?>
<login_user>
<result_code value="1"/>
<error value="Invalid username or password"/>
</login_user>
When I tried to access my PHP script using IE 8, I get this error:
The XML page cannot be displayed Cannot view XML input using style sheet.
Please correct t开发者_运维问答he error and then click the Refresh button, or try again later.
--------------------------------------------------------------------------------
Invalid at the top level of the document. Error processing resource
'http://localhost/kiamobile/login_user.php'. Line 1, P...
<?xml version="1.0" encoding="utf-8" ?>
^
On Google Chrome 10, I get this error:
This page contains the following errors:
error on line 1 at column 6: XML declaration allowed only at the start of the document
On Firefox 4, I get a properly formatted XML output.
On any of the browsers, when I View Source, I can see the correct XML.
I have tried with and without the explicit header. If I remove the call to the PHP header() function, I get these results:
- IE 8: Same error as before
- Firefox 4: Blank screen
- Chrome 10: Blank screen
Again, if I View Source in any of the browsers, I can see the XML. I have tried using text/html instead of application/xml, with no effect.
I have tried generating the XML directly in the PHP code, like this:
<?php
main();
function main()
{
header("Content-type: application/xml");
OutputXML();
exit(0);
}
function OutputXML()
{
echo <<<END
<?xml version="1.0" encoding="utf-8" ?>
<login_user>
<result_code value="1"/>
<error value="Invalid username or password"/>
</login_user>
END;
}
?>
When I do this, I get these results:
- IE 8: Same error
- Firefox 4: I see the formatted XML
- Chrome 10: Blank screen
What am I doing wrong?
Your script may contain unwanted and invisible chars (like BOM) before PHP start tag
Browsers are not made for displaying just any arbitrary XML. They like HTML (which can be XHTML). It is unclear why you want browsers to display those. If it is intended for an and user then you should format those in HTML, if it is for a API (service) then check it with curl/wget/etc and I'm sure the XMl will look the same every time.
精彩评论