2

Why am I getting Illegal offset type error while trying to build an array?

function tassi_parser() {
    $xml=simplexml_load_file('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
    foreach($xml->Cube->Cube->Cube as $tmp) {
        $results[$tmp['currency']] = $tmp['rate'];
    };
    return $results;
};

$tmp['currency'] correctly contains a string that should be used as key so i can't understand what is the problem...

2 Answers 2

2

simplexml_load_file return SimpleXMLElement and every xml element will be an object. Therefore, the type of your $tmp in foreach is "object" (not string), so you need to cast it to string as follows:

(string)$tmp['currency']

You could use the gettype function to retrieve the type of something: http://php.net/manual/en/function.gettype.php

Sign up to request clarification or add additional context in comments.

1 Comment

@Mariano What? Seriously?! I wrote that 15 minutes before this answer!
1

You have to cast it to string like this:

$results[(string)$tmp['currency']] = (string)$tmp['rate'];

Also the ; at the end of the foreach and the function isn't necessary!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.