Reputation: 438
Background:
Creating a website that displays currency rates from various countries around the world.
I have a function that retrieves the rate and the title of the currency from an XML document:
function get_rate(SimpleXMLElement $xml, $x) {
$currency['rate'] = $xml->channel->item[$x]->description;
preg_match('/([0-9]+\.[0-9]+)/', $currency['rate'], $matches);
$rate = $matches[0];
$title['rate'] = $xml->channel->item[$x]->title;
$title = explode('/', $title['rate']);
$title = $title[0];
return array(
$currency[0],
$title[1]
);
// echo $rate . ' ' . $title . '<br />';
}
If I remove the return array an uncomment the echo statement below the function works as expected, but I'm trying to improve this method by using a return type. This method returns both the rate and its title so presume returning an array is the best solution.
I use the following function to echo out the results from functions like the one listed above.
function get_currency_rate($feed) {
$xml = new SimpleXmlElement(file_get_contents($feed));
$rate = get_date($xml);
echo $rate['date'] . '<br />';
$vars = parse_url($feed, PHP_URL_QUERY);
parse_str($vars);
switch ($x) {
case 15:
get_rate($xml, 15); //EUR 15
echo get_rate($xml, $x);
get_rate($xml, 56); //USD 56
echo get_rate($xml, $x);
break;
case 16:
get_rate($xml, 16); //GBP 16
get_rate($xml, 15); //EUR 15
break;
case 56: default :
get_rate($xml, 15); // EUR 15
get_rate($xml, 56); // USD 56
break;
}
}
I'm working on case 15
of the switch statement at the moment. The 2 echo calls in case 15 display Array Array
, which clearly suggests that I'm not accessing the array variable correctly.
I've tried replacing case 15
with the following which I thought would be more syntactically correct to no avial. This also displays Array Array
like the above.
case 15:
get_rate($xml, 15); //EUR 15
echo get_rate($xml, $currency[0]);
get_rate($xml, 56); //USD 56
echo get_rate($xml, $title[1]);
break;
Is the problem because I am declaring different variable names in the get_rate
function?
Upvotes: 2
Views: 265
Reputation: 324620
Use var_dump(get_rate($xml,$x));
and see if that helps you find out what variables you have.
Upvotes: 0
Reputation: 1932
When you echo a non-string, non-numeric type, you will only print out the object type. This is standard behavior across all languages.
It's essentially asking to create a string out of an object, and for more complex types, it's hard to figure out how you turn them into a string, so it just outputs the type.
To get the behavior you want, you'll instead want to echo out the strings in the array, and so reference them directly, like so:
$rate = get_rate($xml, $x);
echo $rate[0] . ' '. $rate[1];
Also, as a side-fact, to see everything that's inside an object, you can also use:
var_dump( get_rate($xml, $x));
This won't be formatted in the prettiest way, but it will allow you to "look into" your object.
Upvotes: 1