简体   繁体   English

PHP - 通过搜索另一个属性标识符获取 XML 元素属性的值

[英]PHP - Get value of an XML element attribute by searching another attribute identifier

I'm trying to get some informations out of a xml string with php.我正在尝试使用 php 从 xml 字符串中获取一些信息。

Heres the example:下面是例子:

<test>
 <item id="29489" name="Strawberry" str="nd93n1jn"/>
 <item id="24524" name="Apple" str="df89ah3n"/>
 <item id="84452" name="Banana" str="27g3vhvr"/>
 <item id="01834" name="Kiwi" str="h32h8329"/>
 <item id="27483" name="Coconut" str="98hf3ubf"/>
 <item id="34892" name="IDK" str="2hbf34wk"/>
</test>

How can I get for example the 'name' string when I know the 'id' string?例如,当我知道“id”字符串时,如何获得“name”字符串?

One way to do this is by parsing the XML into an array structure.一种方法是将 XML 解析为数组结构。 Then just looking at the array values with a simple for loop:然后只需使用简单的 for 循环查看数组值:

$simple = '<test>
 <item id="29489" name="Strawberry" str="nd93n1jn"/>
 <item id="24524" name="Apple" str="df89ah3n"/>
 <item id="84452" name="Banana" str="27g3vhvr"/>
 <item id="01834" name="Kiwi" str="h32h8329"/>
 <item id="27483" name="Coconut" str="98hf3ubf"/>
 <item id="34892" name="IDK" str="2hbf34wk"/>
</test>';

 $p = xml_parser_create();
xml_parse_into_struct($p, $simple, $outArray, $index);
xml_parser_free($p);

$needle="84452";

for($i=0;$i<count($outArray);$i++){ 
    if (array_key_exists('attributes', $outArray[$i])) {
            if($outArray[$i]['attributes']['ID']==$needle){ 
                echo "found it, its name is: " . $outArray[$i]['attributes']['NAME'];
            } 
    } 
}

Note that the XML's attributes are stored in a sub-array called the same way(attributes) when you use the xml_parse_into_struct function.请注意,当您使用xml_parse_into_struct函数时,XML 的属性存储在一个名为相同方式(属性)的子数组中。 Also notice that the array keys when created using xml_parse_into_struct are converted to UPPERCASE by default(look i used uppercase in the search).另请注意,使用 xml_parse_into_struct 创建时的数组键默认转换为大写(看看我在搜索中使用了大写)。 If case is important, you need to add this option just prior to invoking xml_parse_into_struct :如果 case 很重要,您需要在调用xml_parse_into_struct之前添加此选项:

xml_parser_set_option($p,XML_OPTION_CASE_FOLDING,0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM