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.
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;
Here is my Action Item
public function indexAction()
$xml = $this->_xmlModel->getXML($url);
'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
string(6) "20 Feb"
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 ?>
This topic is now closed. New replies are no longer allowed.