douminfu8033 2011-09-21 04:50
浏览 54

PHP中的XML生成问题

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;
}
  • 写回答

1条回答 默认 最新

  • doupinge9055 2011-09-21 06:31
    关注

    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>";
    ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大