为什么我在尝试构建数组时遇到Illegal offset type
错误?
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']
正确包含一个应该用作键的字符串,所以我不明白问题是什么......
simplexml_load_file返回 SimpleXMLElement,每个 xml 元素都将是一个对象。因此,foreach 中$tmp的类型是"对象"(不是字符串),因此您需要将其转换为字符串,如下所示:
(string)$tmp['currency']
您可以使用gettype函数来检索某些东西的类型:http://php.net/manual/en/function.gettype.php
你必须像这样将其转换为字符串:
$results[(string)$tmp['currency']] = (string)$tmp['rate'];
此外,在foreach末尾的;
和函数不是必需的!