Reputation: 63
<?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?
Upvotes: 5
Views: 3898
Reputation: 175
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 ;)
Upvotes: 5
Reputation: 317139
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;
}
}
Upvotes: 1
Reputation: 63
Thanks. I use this method:
$XMLObj = new SimpleXMLElement($XML);
print_r($XMLObj->xpath('/answer/describe/data/code[@xml:lang = "en"]'));
Upvotes: 1
Reputation: 531
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;
}
?>
Upvotes: 5