我有一个xml文件,它包含以下几行:
<myphotos_grid grid="true"><![CDATA[<rows>
<row rowID="1">
<rowAttribute>
<theName>photo-name</theName>
<value/>
</rowAttribute>
<rowAttribute>
<theName>photo-credit</theName>
<value>my credit</value>
</rowAttribute>
<rowAttribute>
<theName>photo</theName>
<value>
<attachment id="1009343343"/>
</value>
</rowAttribute>
</row>
<row rowID="2">
<rowAttribute>
<theName>photo-name</theName>
<value/>
</rowAttribute>
<rowAttribute>
<theName>photo-credit</theName>
<value/>
</rowAttribute>
<rowAttribute>
<theName>photo</theName>
<value>
<attachment id="4432434344"/>
</value>
</rowAttribute>
</row>
</rows>]]></myphotos_grid>
我正在通过PHP函数路径读取xml节点值。我想得到<value>
节点文本值,其<thename>
兄弟节点文本值是photo-credit。我想获得照片信用值。请帮帮我。
PHPcode我试图解析
$this->xpath('myphotos_grid/rows/row/rowattribute/value')
但是我知道我的代码是错误的,因为它需要CDATA
并且它应该取值其slibling节点的文本值是照片信用,我是新手,请帮助
答案 0 :(得分:0)
你需要免费使用&#39;首先是CDATA
中的xml,然后使用xpath()
:
$xml = simplexml_load_string(simplexml_load_string($x));
// assume your original XML in $x
$credits = $xml->xpath("//rowAttribute[theName = 'photo-credit']/value");
迭代数组$credits
以回显值:
foreach ($credits as $credit)
echo $credit . PHP_EOL;
看到它正常工作:https://eval.in/169617
答案 1 :(得分:-1)
奇怪的是,它不适用于通常的事情:
$xml = simplexml_load_string($xml_string, 'SimpleXMLElement', LIBXML_NOCDATA);
请改用:
$xml_string = '<myphotos_grid grid="true"><![CDATA[<rows> <row rowID="1"> <rowAttribute> <theName>photo-name</theName> <value/> </rowAttribute> <rowAttribute> <theName>photo-credit</theName> <value>my credit</value> </rowAttribute> <rowAttribute> <theName>photo</theName> <value> <attachment id="1009343343"/> </value> </rowAttribute> </row> <row rowID="2"> <rowAttribute> <theName>photo-name</theName> <value/> </rowAttribute> <rowAttribute> <theName>photo-credit</theName> <value/> </rowAttribute> <rowAttribute> <theName>photo</theName> <value> <attachment id="4432434344"/> </value> </rowAttribute> </row></rows>]]></myphotos_grid>';
$doc = new DOMDocument();
$doc->loadXML($xml_string);
$xml_nodes = $doc->textContent;
$xml = new SimpleXMLElement($xml_nodes);
$value = $xml->xpath('//rowAttribute/theName[contains(.,"photo-credit")]/following-sibling::value/text()')[0];
echo (string) $value; // my credit