我有以下xml结构:
<stores>
<store>
<name></name>
<address></address>
<custom-attributes>
<custom-attribute attribute-id="country">Deutschland</custom-attribute>
<custom-attribute attribute-id="displayWeb">false</custom-attribute>
</custom-attributes>
</store>
</stores>
如何获取"displayWeb“的值?
发布于 2012-02-06 23:17:24
最好的解决方案是使用PHP DOM,你可以循环遍历所有商店:
$dom = new DOMDocument();
$dom->loadXML( $yourXML);
// With use of child elements:
$storeNodes = $dom->documentElement->childNodes;
// Or xpath
$xPath = new DOMXPath( $dom);
$storeNodes = $xPath->query( 'store/store');
// Store nodes now contain DOMElements which are equivalent to this array:
// 0 => <store><name></name>....</store>
// 1 => <store><name>Another store not shown in your XML</name>....</store>
它们使用DOMDocument
properties和DOMElement
属性childNodes
或DOMXPath
。一旦你有了所有的存储,你可以使用foreach
循环遍历它们,获得所有元素,并使用getElementsByTagName
将它们存储到关联数组中
foreach( $storeNodes as $node){
// $node should be DOMElement
// of course you can use xPath instead of getAttributesbyTagName, but this is
// more effective
$domAttrs = $node->getAttributesByTagName( 'custom-attribute');
$attributes = array();
foreach( $domAttrs as $domAttr){
$attributes[ $domAttr->getAttribute( 'attribute-id')] = $domAttr->nodeValue;
}
// $attributes = array( 'country' => 'Deutschland', 'displayWeb' => 'false');
}
或者直接使用xPath
选择属性
// Inside foreach($storeNodes as $node) loop
$yourAttribute = $xPath->query( "custom-attribute[@attribute-id='displayWeb']", $node)
->item(0)->nodeValue; // Warning will cause fatal error when missing desired tag
或者,当您只需要整个文档中的一个值时,您可以使用(正如Kirill Polishchuk建议的那样):
$yourAttribute = $xPath->query( "stores/store/custom-attributes/custom-attribute[@attribute-id='displayWeb']")
->item(0)->nodeValue; // Warning will cause fatal error when missing desired tag
仔细阅读手册,了解什么时候返回什么类型,以及哪个属性包含什么。
发布于 2012-02-06 22:48:30
例如,我可以解析XML DOM。http://php.net/manual/en/book.dom.php
发布于 2012-02-06 22:58:10
您可以使用XPath:
stores/store/custom-attributes/custom-attribute[@attribute-id='displayWeb']
https://stackoverflow.com/questions/9161866
复制相似问题