用php解析XML [英] xml parsing with php

查看:88
本文介绍了用php解析XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to create a new simplified xml based on an existing one: (using "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"混为一谈,因此我尝试使用以下解决方案->

Because there are always colons in the element-tags, it will mess with "simpleXml", I tried to use the following solution->link.

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

How can I create a new xml with this structure:

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

指令元素"的内容来自于以前的"xls:指令元素".

the "instruction-element" gets its content from the former "xls:Instruction-element".

这是更新的代码: 但不幸的是,它永远不会循环通过:

Here is the updated code: But unfortunately it never loops through:

$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();

如果我留下"@",则没有错误消息……

there is no error-message, if I leave the "@"…

推荐答案

您可以使用xpath简化操作.不知道全部细节,我不知道它是否在所有情况下都有效:

You could use xpath to simplify things. Without knowing the full details, I don't know if it will work in all cases:

$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不同.您需要使用类似以下的命名空间:

The file at http://www.gps.alaingroeneweg.com/route.xml is not the same as the XML you have in your question. You need to use a namespace like:

$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>

这篇关于用php解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆