tags:

views:

37

answers:

4

Hi, everyone. 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?

A: 

Have a look at the PHP SAX parser decribed here.

Thariama
Can parse xml:lang, using SimpleXMLElement?
Sergey
yes, have a look at http://www.php.net/manual/en/function.xml-parse.php
Thariama
A: 

Has been answered before:

$dom =new DOMDocument;
$dom->loadXML( $xml );
$xPath = new DOMXPath( $dom );
$nodes = $xPath->query( '/answer/describe/data/code[@xml:lang = "en"]' );
foreach( $nodes as $node ) {
    echo $node->nodeValue; 
}

Alternative without XPath:

$dom =new DOMDocument;
$dom->loadXML ($xml );
foreach( $dom->getElementsByTagName( 'code' ) as $node ) {
    if( $node->getAttribute( 'xml:lang' ) === 'en') {
        echo $node->nodeValue;
    }
}
Gordon
+2  A: 

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"&gt;
    <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;
}
?>
Oleg
A: 

Thanks. I use this method:

$XMLObj = new SimpleXMLElement($XML);
print_r($XMLObj->xpath('/answer/describe/data/code[@xml:lang = "en"]'));
Sergey
Good stuff. Welcome to stack :)
Oleg