0

I have this 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

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

Any ideas? Thank you.

1 Answer 1

5

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.

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?

All CATEGORY nodes:

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

Only the CATEGORY nodes name attributes:

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

Only the CATEGORY nodes that have a name attribute:

foreach($xml->xpath('//CATEGORY[@name]') as $category)
{
    echo $category['name'] . '<br />';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Thank you so much! The code for all CATEGORY nodes is what I am looking for and your explanation has helped me understand the way this works.
One thing worth adding to this is that if doing anything other than echoing your results, remember to cast to string once you are done traversing the XML (e.g. $my_category_list[] = (string)$category['name'];) otherwise you will be passing around SimpleXML objects which may have undesirable consequences.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.