I wrote xml to a file using php, and then I sent the file data as a response to the client's browser. But, I'm getting the following error: XML Parsing Error: not well-formed Below, is my code. Any way to fix this?
$file= fopen("result.xml", "w");
$_xml ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
$_xml .="<friends>";
$timestamp = time();
$_xml.="<date>".date("F jS, Y", $timestamp)."</date>"; //Like December 23rd, 2009
$_xml .="<total>".$totalResults."</total>";
foreach($friendList as $key => $value) { /*$friendList contains key value pairs*/
$_xml.="<friend>";
$_xml.="<name>".$key."</name>";
$_xml.="<webpage>".$value."</webpage>";
$_xml.="</friend>";
}
$_xml .="</friends>";
fwrite($file,$_xml);
fclose($file);
//Send the xml file as response
header('Content-type: text/xml');
readfile('result.xml');
Tha开发者_如何学编程nk You
The snippet of code you posted works fine without any data in $friendList
, so the problem lies with your data.
I'm going to guess that you're outputting URLs inside your <webpage></webpage>
tags, which could contain characters such as &
. XML requires that the & ' " > <
characters be escaped. Fortunately, htmlspecialchars() does exactly that.
Try using this:
$_xml.="<webpage>".htmlspecialchars($value,ENT_QUOTES)."</webpage>";
It's not a bad idea to escape your other pieces of data as well.
You have a closing "friends" tag that is never opened. Change the relevant snipper to:
$_xml .="<friends>";
foreach($friendList as $key => $value) { /*$friendList contains key value pairs*/
$_xml.="<friend>";
$_xml.="<name>".$key."</name>";
$_xml.="<webpage>".$value."</webpage>";
$_xml.="</friend>";
}
$_xml .="</friends>";
Using somethring like XMLWriter makes it much easier and cleaner to write this kind of code:
$xml_writer = new XMLWriter();
$xml_writer->openMemory();
$xml_writer->startDocument('1.0', 'UTF-8', 'yes');
...
$xml_writer->startElement('friends');
...
$xml_writer->endElement(); //friends
...
$data = $xml_writer->outputMemory();
echo($data);
Its possible that the array $friendList
has keys and/or values have tag(s) in them. If that is the case our XML string $_xml
will not be a valid XML.
The XML im getting is like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<friends><date>December 23rd, 2009</date><total>2</total><friend><name>ABC</name><url>http://www.somesite.org/abc</url></friend><friend><name>PQR</name><url>http://www.somesite.org/pqr</url></friend></friends>
There is no reason to write into a file before serving it. Just output it directly to the client:
$_xml .="</friends>";
//Send the xml file as response
header('Content-type: text/xml');
echo $_xml;
精彩评论