开发者

xml parsing with php

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> 

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

How can I create a new xml with this structure:

<main>
  <instruction>Start</in开发者_如何学Pythonstruction>
  <instruction>End</instruction>
</main>

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 "@"…


/* 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();


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

Output:

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

Edit: 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();

Output:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜