Я хотел бы создать новый упрощенный 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», я попытался использовать следующую ссылку solution->.
Как я могу создать новый xml с этой структурой:
 <main> <instruction>Start</instruction> <instruction>End</instruction> </main> 
«элемент-инструкция» получает свое содержание из прежнего «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(); 
нет сообщения об ошибке, если я оставлю «@» …
Вы можете использовать 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> 
 /* 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();