用php解析xml

时间:2010-12-02 16:48:09

标签: php xml parsing simplexml

我想基于现有的xml创建一个新的简化xml: (使用“simpleXml”)

<?xml version="1.0" encoding="UTF-8"?>
<xls:XLS>
   <xls:RouteInstructionsList>
     <xls:RouteInstruction>
       <xls:Instruction>Start</xls:Instruction>
     </xls:RouteInstruction>
   </xls:RouteInstructionsList>
  <xls:RouteInstructionsList>
     <xls:RouteInstruction>
       <xls:Instruction>End</xls:Instruction>
     </xls:RouteInstruction>
   </xls:RouteInstructionsList>
</xls:XLS> 

因为元素标签中总是有冒号,所以它会混淆“simpleXml”,我尝试使用以下解决方案 - &gt; link

如何使用此结构创建新的xml:

<main>
  <instruction>Start</instruction>
  <instruction>End</instruction>
</main>

“instruction-element”从前面的“xls:Instruction-element”获取其内容。

这是更新的代码: 但不幸的是它永远不会遍历:

$source = "route.xml";
$xmlstr = file_get_contents($source);
$xml = @simplexml_load_string($xmlstr);
$new_xml = simplexml_load_string('<main/>');
foreach($xml->children() as $child){
   print_r("xml_has_childs");
   $new_xml->addChild('instruction', $child->RouteInstruction->Instruction);
}
echo $new_xml->asXML();

如果我离开“@”......

,则没有错误消息

2 个答案:

答案 0 :(得分:3)

/* the use of @ is to suppress warning */
$xml = @simplexml_load_string($YOUR_RSS_XML);
$new_xml = simplexml_load_string('<main/>');
foreach ($xml->children() as $child)
{
  $new_xml->addChild('instruction', $child->RouteInstruction->Instruction);
}

/* to print */
echo $new_xml->asXML();

答案 1 :(得分:1)

您可以使用xpath来简化操作。在不知道完整细节的情况下,我不知道它是否适用于所有情况:

$source = "route.xml";
$xmlstr = file_get_contents($source);
$xml = @simplexml_load_string($xmlstr);
$new_xml = simplexml_load_string('<main/>');
foreach ($xml->xpath('//Instruction') as $instr) {
   $new_xml->addChild('instruction', (string) $instr);
}
echo $new_xml->asXML();

输出:

<?xml version="1.0"?>
<main><instruction>Start</instruction><instruction>End</instruction></main>

编辑:http://www.gps.alaingroeneweg.com/route.xml处的文件与您问题中的XML不同。您需要使用如下命名空间:

$xml = @simplexml_load_string(file_get_contents('http://www.gps.alaingroeneweg.com/route.xml'));
$xml->registerXPathNamespace('xls', 'http://www.opengis.net/xls'); // probably not needed 
$new_xml = simplexml_load_string('<main/>');
foreach ($xml->xpath('//xls:Instruction') as $instr) {
  $new_xml->addChild('instruction', (string) $instr);
}
echo $new_xml->asXML();

输出:

<?xml version="1.0"?>
<main><instruction>Start (Southeast) auf Sihlquai</instruction><instruction>Fahre rechts</instruction><instruction>Fahre halb links - Ziel erreicht!</instruction></main>