简体   繁体   English

如何使用php simpleXML获取多个XML元素属性

[英]how to get multiple XML elements attributes with php simpleXML

I have this XML 我有这个XML

<STOREITEMS>
  <CREATED value="Tue Oct 9 5:30:01 BST 2012">
    <CATEGORY id="442" name="Hen And Stag Nights"></CATEGORY>
    <CATEGORY id="69" name="Games"></CATEGORY>
    <CATEGORY id="252" name="Love Zone"></CATEGORY>
    <CATEGORY id="202" name="Spotlight  Items"></CATEGORY>
  </CREATED>
</STOREITEMS>

I need to get the Category - name attribute with PHP 我需要使用PHP获取Category-name属性

So far I have this 到目前为止,我有这个

$xml = simplexml_load_file("http://www.dropshipping.co.uk/catalog/xml_id_multi_info.xml");

foreach($xml->CATEGORY['name']->attributes() as $category)    
{    
    echo $category; 
}

This however returns Fatal error: Call to a member function attributes() on a non-object 但是,这将返回致命错误:在非对象上调用成员函数attribute()

Any ideas? 有任何想法吗? Thank you. 谢谢。

The CATEGORY nodes are nested inside the CREATED node, so you'd need to access it there, and accessing CATEGORY['name']->attributes() makes no sense, since that would try to access non-existent attributes on the name attribute of the first CATEGORY node. CATEGORY节点嵌套在CREATED节点内,因此您需要在其中访问它,并且访问CATEGORY['name']->attributes()毫无意义,因为这将尝试访问name上不存在的属性第一个CATEGORY节点的属性。

So do you want to retreive the name attribute values of all CATEGORY nodes, or all CATEGORY nodes, or maybe only those CATEGORY nodes that have a name attribute? 那么,您是否要检索所有CATEGORY节点或所有CATEGORY节点的名称属性值,或者仅检索那些具有name属性的CATEGORY节点的name属性值?

All CATEGORY nodes: 所有CATEGORY节点:

foreach($xml->CREATED->CATEGORY as $category)
{
    echo $category['name'] . '<br />';
}

Only the CATEGORY nodes name attributes: CATEGORY节点的名称属性:

foreach($xml->xpath('//CATEGORY/@name') as $name)
{
    echo $name . '<br />';
}

Only the CATEGORY nodes that have a name attribute: 仅具有名称属性的CATEGORY节点:

foreach($xml->xpath('//CATEGORY[@name]') as $category)
{
    echo $category['name'] . '<br />';
}

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

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