最好的解决方案是使用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
仔细阅读手册,了解什么时候返回什么类型,哪个属性包含什么。