Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml:lang parse in PHP

Tags:

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>

I need get nodes value, there xml:lang="en". How can do it in PHP?

like image 658
Sergey Avatar asked Oct 22 '10 11:10

Sergey


2 Answers

Yes, SimpleXML works but try adding the xml namespace if you run into trouble.

E.g.:

<?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;
}
?>
like image 80
Oleg Avatar answered Oct 17 '22 09:10

Oleg


XPath has a special construct for dealing with xml:lang attribute:

$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];

P.S. greetings to the Sirena ;)

like image 5
Kit Avatar answered Oct 17 '22 08:10

Kit