Cant echo SimpleXMLElement propeties

Hey guys,

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:

https://developer.terapeak.com/docs/read/researchapi/GetHotProducts

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!!

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)…

Hi Lemon,

Thanks for your reply, I got there in the end… this works:


foreach($this->strXmlResponseXml->HotProducts->Product as $value)
		{
			$htmlOutput;
			$htmlOutput = ucfirst($value->Keywords) . "<br />";
			echo $htmlOutput;
		}

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!

You have a weird PHP book :D. Glad you’ve sorted it out finally!