2013-12-12 32 views
2

我想使用此代碼的XML提要創建標題的數組的數組:設置從simple_xml數據

$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); 

回聲$遊戲 - > {「標題」}。 「\ n」 個;返回正確的標題,但標題設置爲數組,當我得到這個垃圾郵件:

Array 
(
    [0] => SimpleXMLElement Object 
     (
      [0] => SimpleXMLElement Object 
       (
       ) 

     ) 

    [1] => SimpleXMLElement Object 
     (
      [0] => SimpleXMLElement Object 
       (
       ) 

     ) 

    [2] => SimpleXMLElement Object 
     (
      [0] => SimpleXMLElement Object 
       (
       ) 

     ) 

我是不是設置這個數組時失去了一些東西?

回答

2

使用此:

$on_sale[] = $game->{'title'}->__toString();

甚至更​​好的(在我看來):

$on_sale[] = (string) $game->{'title'};

PHP不知道你想要的字符串值,當你添加的對象到陣列,所以__toString()不會像調用echo時那樣自動調用。當您將對象投射到string時,會自動調用__toString()

FYI:你並不真的需要花括號要麼,這個工作正常,我:

$on_sale[] = (string) $game->title;

+0

這是真棒謝謝! – NaughtySquid

+0

不客氣! –