2011-11-06 41 views
0

我有這個代碼用於解析XML URL並將輸出存儲在$查詢變量中。具有simplexml對象的數組。如何使用foreach循環獲取它

$url = 'http://www.slideshare.net/api/2/search_slideshows?api_key=GRCsS0fPo& 
ts=1320547556&hash=cf362f863d1f15e84c7a520804f7826731f958c4&q=electrical+engineering& 
page=4&download=0&items_per_page=25'; 

echo $url; 

$ch=curl_init(); 

curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_USERAGENT, 'Your application name'); 

$query = curl_exec($ch); 

curl_close($ch); 
$array = (array) simplexml_load_string($query); 
echo '<pre>'; 
print_r($array); 

當我打印使用的print_r($陣列)這個數組它給了我

Array 
    (
    [Meta] => SimpleXMLElement Object 
    (
    [Query] => php programming 
     [ResultOffset] => SimpleXMLElement Object 
     (
     ) 

     [NumResults] => 25 
     [TotalResults] => 36839 
    ) 

     [Slideshow] => Array 
    (
      [0] => SimpleXMLElement Object 
     (
      [ID] => 1966058 
      [Title] => title here 
      [Description] => description here 
      [Status] => 2 
      [Username] =>usrname 
      [URL] => url here 
      [ThumbnailURL] => a url 
      [ThumbnailSmallURL] => a url 
       [Embed] => some embed code 
    ) 
    [1] => SimpleXMLElement Object 
     (
      [ID] => 1966058 
      [Title] => title here 
      [Description] => description here 
      [Status] => 2 
      [Username] =>usrname 
      [URL] => url here 
      [ThumbnailURL] => a url 
      [ThumbnailSmallURL] => a url 
      [Embed] => some embed code 
    ) 

現在我想取這個數組並使用它的每一個值。我想要這個數組的所有節點值。所以如何使用foreach循環獲取這個數組。

+0

重複http://stackoverflow.com/questions/8023179/how-to-fetch-this-array-using-foreach-loop – Vikk

回答

0

我認爲最好是使用SimpleXML XPath方法而不是直接遍歷數組。

+0

但如何?你可以修改我的代碼: – manishjangir

+0

'foreach($ array-> xpath('// Slideshow')as $ slideShow){$ {slideShow-> username; }' – nevvermind

+0

這工作正常,但現在又出現了另一個問題,大部分時間由curl提供的數組變爲null。問題是什麼。我正在本地主機上運行整個腳本。 – manishjangir

相關問題