Zend Framework - Array to Object

I am trying to write my first ZF application part of the application is to retrieve XML data.

Here is a sample file of what is contained in the XML.


<response>
	<totalresults>3017</totalresults>
	<results>
		<result>
			<title>Title1</title>
			<date>20 Feb</date>
		</result>
		<result>
			<title>Title2</title>
			<date>21 Feb</date>
		</result>
	</results>
</response>

I am using DOM and here is my PHP


public function getXML($xml)
{
$reader = new DOMDocument();
$reader->load($url);  //Loads the Above XML

$i = 0;
		
$res['totalresults']	= $reader->getElementsByTagName('totalresults')->item(0)->nodeValue;

	foreach ($reader->getElementsByTagName('result') as $node)
	{
		$res[$i]['title'] = ucwords(strtolower($node->getElementsByTagName('title')->item(0)->nodeValue));
		$res[$i]['date'] = $node->getElementsByTagName('date')->item(0)->nodeValue;

		$i++;
	}

return $res;
}


Here is my Action Item



public function indexAction()
{

	$xml = $this->_xmlModel->getXML($url);
	var_dump($xml);
	$this->view->assign(array(
		'xmlRes' => $xml,
		)
	);
}

Finally this is my View Script.



<?php foreach ($this->xmlRes as $xmlRes): ?>
	<div><?php echo $this->escape($xmlRes->title); ?></div>
	<div><?php echo $this->escape($xmlRes->date); ?></div>
<?php endforeach ?>


Here is the Error I get when I visit the requested page

Trying to get property of non-object

Results from the vardump


array(3) {
  ["totalresults"]=>
  string(4) "3017"
  [0]=>
  array(2) {
    ["title"]=>
    string(6) "Title1"
    ["date"]=>
    string(6) "20 Feb"
  }
  [1]=>
  array(2) {
    ["title"]=>
    string(6) "Title2"
    ["date"]=>
    string(6) "21 Feb"
  }
}

I realize that I am trying to display an array as an object. I don’t understand how I can make that array into an object or simply display my array. I am hoping this is an easy fix I’ve searched high and low but haven’t been able to find the answer.

The $xmlRes variable contains array and not an object, so accessing values of the array by using “->” is incorrect, you need to access values by using “” instead.

The $xmlRes array first value is a string and not an array (the value with key “totalresults”), the other values of the array are arrays. You need to skip the first value of the array in the view / or remove it from the array in controller action.

Try this in your view (not tested but it should work):

<?php foreach ($this->xmlRes as $key => $xmlRes): ?> 
	<?php if ($key == 'totalresults') continue ?>
	<div><?php echo $this->escape($xmlRes['title']); ?></div> 
	<div><?php echo $this->escape($xmlRes['date']); ?></div> 
<?php endforeach ?>

That was it thank you.