简体   繁体   中英

Problem with XML generation in PHP

I am new to XML Parsing so kindly point out any mistakes in my question.

  1. I have an XML file which I cannot change.
  2. I have written a php script that obtains the user input through get parameter and then searches the suitaible entry in the xml file. Once it finds the entry based on the get parameter it outputs suitaible XML for that entry.
  3. The script works fine for most cases which is confirmed by the browser showing specific XML data corresponding to the ID when the script is called in the browser with a get parameter.

Problem: In some cases the XML file contains & . When these entries are called for an XML error is generated by the browser near the ampersand sign. I want to know what exactly is causing the problem and preventing the formation of well formed XML.

Here is my php code...

for($j=0;$j<$length;$j++)
{
    $name=$parent->childNodes->item($j)->nodeName;
    for($k=0;$k<$num;$k++)
    {
        if($name==$elements_reqd[$k])
        {
            $value=$parent->childNodes->item($j)->textContent;
            $info=array_push_assoc($info,$elements_reqd[$k],$value);
        }
    }

}


echo "<LISTING>";
foreach($info as $key => $value)
{
    echo "<$key>$value</$key>";
}
echo "</LISTING>";


function array_push_assoc(&$array, $key, $value){
$array[$key] = $value;
return $array;
}

There are 5 characters that must be escaped in XML , & being one of them. If $value is a string like "This & That" it should appear in XML as "This &amp; That"

One way to achieve XML escaping in PHP is:

echo "<$key>".htmlspecialchars($value)."</$key>";

Also, before echoing your XML output, set the header for XML and add the document declaration so the browser knows for sure XML is being delivered:

header ("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="ISO-8859-1"?>';
echo "<LISTING>";
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM