johnuk — 2012-11-14T11:03:28-05:00 — #1
Im new to using SimpleXMLElement and its driving me up the wall! I am using cUrl to access an API, and I have the returned XML loaded into a SimpleXMLElement ready to be output. The xml returned looks like this:
http://img402.imageshack.us/img402/1493/xmlh.jpg and is structured thus:
I can do a print_r on it no problem e.g. print_r($responseXml->HotProducts->Product) which works fine. But if I try to loop through and echo values e.g. 'keywords', 'CatagoryName' etc for each product object I get nothing on the screen whatsoever.
This is driving me up the wall because im used to working with objects and I cant see whats going wrong.
Any help much appreciated!!
lemon_juice — 2012-11-14T14:20:10-05:00 — #2
If you posted some sample code that doesn't work for you it would be much easier. SimpleXML is a convenient class but has a lot of magic behind the scenes which makes it tricky to use sometimes. Generally, multiple element nodes are objects which implement Iterator and ArrayAccess and can be looped with foreach() - other types of looping may not work since they are not real arrays. Single nodes are objects which implement magic __toString() method which convert them to strings in string context. In most cases you can use them directly as strings but sometimes a real string may be required and then you have to cast them with (string)...
johnuk — 2012-11-14T14:26:20-05:00 — #3
Thanks for your reply, I got there in the end.. this works:
foreach($this->strXmlResponseXml->HotProducts->Product as $value)
$htmlOutput = ucfirst($value->Keywords) . "<br />";
The PHP book im reading said I should access SimpleXMLElement Object attributes with array notation e.g. $someObj['someProperty'], but I just used $someObj->someProperty and that worked!
lemon_juice — 2012-11-14T18:14:37-05:00 — #4
You have a weird PHP book :D. Glad you've sorted it out finally!