我正在尝试使用以下代码从 xml feed 创建标题数组:
$url = 'https://indiegamestand.com/store/salefeed.php';
$xml = simplexml_load_string(file_get_contents($url));
$on_sale = array();
foreach ($xml->channel->item as $game)
{
echo $game->{'title'} . "\n";
$on_sale[] = $game->{'title'};
}
print_r($on_sale);
echo $game->{'title'} 。 “\n”;返回正确的标题,但是当将标题设置为数组时,我收到了这样的垃圾邮件:
Array
(
[0] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
(
)
)
[1] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
(
)
)
[2] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
(
)
)
设置此数组时我是否遗漏了某些内容?
最佳答案
使用这个:
$on_sale[] = $game->{'title'}->__toString();
或者甚至更好(在我看来):
$on_sale[] = (string) $game->{'title'};
当您将对象添加到数组时,PHP 不知道您需要字符串值,因此 __toString()
不会像 echo< 中那样自动调用
调用。当您将对象转换为 string
时,会自动调用 __toString()
。
仅供引用:您也不需要大括号,这对我来说效果很好:
$on_sale[] =(字符串)$game->title;
关于php - 从 simple_xml 数据设置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20544919/