如何解析php中的xml?

时间:2015-12-04 15:37:10

标签: php xml codeigniter parsing

我正在使用Codeigniter 3,我试图获取xml的值。我没办法......

我尝试使用此代码获取值。

        $dom = new DOMDocument();
        $dom->loadlXML($xml);
        $img = $dom->getElementsByTagName('sonucKodu')->item(0);
        echo $img->attributes->getNamedItem("value")->value;

我的xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<SYSMessage xmlns:ext="http://nxxx/Cd/Extensions/1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <messageType code="1" value="xxx" codeSystemGuid="0a9ba485-e7e0-4abb-9c86-0a14fd364bb8" version="1" />
   <documentGenerationTime value="201512041717" />
   <author>
      <healthcareProvider code="0" value="SYS" codeSystemGuid="c9dbe1cb-57cb-48fb-bdd3-d622e0e304c6" version="1" />
   </author>
   <recordData>
      <KayitCevabi>
         <sonucKodu value="E2003" />
         <sonucMesaji value="TakipNo geçerli değil" />
      </KayitCevabi>
   </recordData>
</SYSMessage>

我只需要属性sonucKodu的值。它必须是E2003

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我使用的是SimpleXMLElement而不是Domdocument。

$xml = '<?xml version="1.0" encoding="UTF-8"?>
<SYSMessage xmlns:ext="http://nxxx/Cd/Extensions/1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <messageType code="1" value="xxx" codeSystemGuid="0a9ba485-e7e0-4abb-9c86-0a14fd364bb8" version="1" />
   <documentGenerationTime value="201512041717" />
   <author>
      <healthcareProvider code="0" value="SYS" codeSystemGuid="c9dbe1cb-57cb-48fb-bdd3-d622e0e304c6" version="1" />
   </author>
   <recordData>
      <KayitCevabi>
         <sonucKodu value="E2003" />
         <sonucMesaji value="TakipNo geçerli değil" />
      </KayitCevabi>
   </recordData>
</SYSMessage>';
$s_xml = new SimpleXMLElement($xml);
//print_r($s_xml);
echo $s_xml->recordData->KayitCevabi->sonucKodu['value'];

输出:

  

E2003

演示:https://eval.in/480525

答案 1 :(得分:0)

<?php
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";

$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
print_r($xml);
?>