gpt4 book ai didi

PHP:获取xml的属性值

转载 作者:可可西里 更新时间:2023-11-01 00:50:15 24 4
gpt4 key购买 nike

我有以下 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”的值?

最佳答案

最好的解决方案是使用 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 propertiesDOMElement属性 childNodesDOMXPath .拥有所有存储后,您可以使用 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

仔细阅读手册以了解何时返回什么类型以及哪个属性包含什么。

关于PHP:获取xml的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9161866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com