PHP XML: Illegal Offset, but it is in array?

2019-07-26 06:23发布

问题:

$dagen = array(
    'Mon' => 'Maandag',
    'Tue' => 'Dinsdag',
    'Wed' => 'Woensdag',
    'Thu' => 'Donderdag',
    'Fri' => 'Vrijdag',
    'Sat' => 'Zaterdag',
    'Sun' => 'Zondag'
);

foreach ($xml->verwachtingen->verwachting as $verwachting) {
    $graden = $verwachting->maxtempGRC - $verwachting->mintempGRC;
    $graden = $graden / 2;
    $graden = $graden + $verwachting->mintempGRC;
    $dag = $verwachting->dagvdweek;

    echo 'Op '. $dagen[$dag] .' wordt het '. $graden .' graden';
}

$xml is the XML document loaded using SimpleXMLElement.

Now, help me out here. When i echo $dag it displays 'Fri' because it is Friday. So i try to convert the english words of the days to my language (dutch). But it doesn't seem to work, because i get this:

Warning: Illegal offset type in C:\data\home\www\awnl-xml\index.php on line 21
Op wordt het 18.5 graden
Warning: Illegal offset type in C:\data\home\www\awnl-xml\index.php on line 21
Op wordt het 18 graden
Warning: Illegal offset type in C:\data\home\www\awnl-xml\index.php on line 21
...

Does someone know why i get this error? Thanks.

回答1:

$dag will be an object, of type SimpleXMLElement. Objects are not allowed to be used for array keys, which is why you are getting that "Illegal offset type" warning.

The object must first be cast to a suitable type before being used like that, in your case it should be a string.

$dag = (string) $verwachting->dagvdweek;