<?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>
我需要获取节点值,有xml:lang =“en”。怎么能在PHP中做到这一点?
答案 0 :(得分:5)
是的,SimpleXML有效,但如果遇到麻烦,请尝试添加xml namespace。
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;
}
?>
答案 1 :(得分: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];
P.S。对Sirena的问候;)
答案 2 :(得分:1)
之前已经回答:
$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;
}
没有XPath的替代方案:
$dom =new DOMDocument;
$dom->loadXML ($xml );
foreach( $dom->getElementsByTagName( 'code' ) as $node ) {
if( $node->getAttribute( 'xml:lang' ) === 'en') {
echo $node->nodeValue;
}
}
答案 3 :(得分:1)
感谢。 我用这个方法:
$XMLObj = new SimpleXMLElement($XML);
print_r($XMLObj->xpath('/answer/describe/data/code[@xml:lang = "en"]'));
答案 4 :(得分:0)