парсинг xml с php - PullRequest
       1

парсинг xml с php

0 голосов
/ 02 декабря 2010

Я хотел бы создать новый упрощенный 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"", Я попытался использовать следующее решение -> ссылка .

Как мне создать новый xml с такой структурой:

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

the" инструкция-элемент"получает свое содержимое от прежнего" 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 ]

3 голосов
/ 02 декабря 2010
/* 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 голос
/ 03 декабря 2010

Вы можете использовать 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>
...