xml:lang在PHP中解析

Ser*_*gey 5 php xml

<?xml version="1.0" encoding="UTF-8"?>
  <answer>
    <describe data="aircompany">
      <data>
        <code xml:lang="ru">FW</code>
        <code xml:lang="en">FW</code>
      </data>
      <data>
        <code xml:lang="ru">UT</code>
        <code xml:lang="en">??</code>
      </data>
    </describe>
  </answer>
Run Code Online (Sandbox Code Playgroud)

我需要获取节点值,有xml:lang ="en".怎么能在PHP中做到这一点?

小智 5

是的,SimpleXML有效,但如果遇到麻烦,请尝试添加xml命名空间.

例如:

<?php
$xmlstr = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<answer xmlns:xml="http://www.w3.org/XML/1998/namespace">
    <describe data="aircompany">
      <data>
        <code xml:lang="ru">??</code>
        <code xml:lang="en">FW</code>
      </data>
      <data>
        <code xml:lang="ru">??</code>
        <code xml:lang="en">UT</code>
      </data>
    </describe>
</answer>
XML;

$xml = new SimpleXMLElement($xmlstr);

foreach ($xml->xpath('//data/code[@xml:lang="en"]') as $code) {
    echo $code, '<br/>', PHP_EOL;
}
?>
Run Code Online (Sandbox Code Playgroud)


Kit*_*Kit 5

XPath有一个特殊的构造来处理xml:lang属性:

$xml = new SimpleXMLElement($strXML);
$data = $xml->describe->data[0];
$elCode = $data->xpath("code[lang('en')]"); // returns array of SimpleXMLElement
assert(count($elCode)==1);
$code_en = (string) $elCode[0];
Run Code Online (Sandbox Code Playgroud)

PS问候Sirena;)