Reputation: 2110
Consider the following PHP function which should load an object from XML file chosen in regards of language:
function item1($Langu){
if($Langu=='bg'){
$urlD = "someurl/rss1.php";
$xmlD = simplexml_load_file(cacheFetch($urlD,'cachedfeedDBG.xml',3600));
$itemD = '';
if($xmlD === FALSE)
{$itemD = '';}
else
{$itemD = $xmlD->channel->item;}
}
else{
$urlD = "someurl/rss2.php";
$xmlD = simplexml_load_file(cacheFetch($urlD,'cachedfeedDEN.xml',3600));
$itemD = '';
if($xmlD === FALSE)
{$itemD = '';}
else
{$itemD = $xmlD->channel->item;}
}
return $itemD;
}
When I echo the function result nothing shows. Maybe i should wrap the function in class? Please don't bash me as I'm a newbie in the field of OOP PHP. Any help making the function work is greatly appreciated.
Upvotes: 0
Views: 1377
Reputation: 3441
It is very possible that the object parameter simply doesn't exist. Do this:
$result = item1($Langu);
echo "<pre>" . print_r($result, true) . "</pre>";
function item1($Langu) {
if ($Langu == 'bg') {
$urlD = "someurl/rss1.php";
$xmlD = simplexml_load_file(cacheFetch($urlD, 'cachedfeedDBG.xml', 3600));
}
else {
$urlD = "someurl/rss2.php";
$xmlD = simplexml_load_file(cacheFetch($urlD, 'cachedfeedDEN.xml', 3600));
}
return $xmlD;
}
This will show you most of the properties of the object. Now unfortunately SimpleXML returns a resource, so there will also be a lot of information that is hidden. This should help get you started though. There is a way to get ahold and output all the hidden info. Check out the comments below the function on PHP.net. (http://us3.php.net/manual/en/function.simplexml-load-file.php)
Also the space bar is your friend not your enemy, please learn to use it along with other clean coding habits (such as descriptive variable names). This will make you and other programmers that look at your code much happier in the long run.
Upvotes: 1
Reputation: 4730
1: 2 of your return cases return an empty string, so echo'ing the return would correctly yield nothing.
2: If you are trying to output the contents of the object, you must use either print_r() or var_dump()
3: Simple XML is a bit weird in that a var_dump or print_r won't show all the properties of the object ( https://www.php.net/manual/en/simplexmlelement.attributes.php - "SimpleXML has made a rule of adding iterative properties to most methods. They cannot be viewed using var_dump() or anything else which can examine objects." ) - so you may benefit by looking at what you have available - http://www.php.net/manual/en/ref.simplexml.php - the first comment on that page has a helpful function that may assist you in accomplishing a dump of the object:
A quick snippet which converts XML Object into array:
<?php
function xml2array ( $xmlObject, $out = array () )
{
foreach ( (array) $xmlObject as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
return $out;
}
?>
Have fun! ;-)
Upvotes: 2