2013-08-17 53 views
0

我試圖解析RSS各種來源的飼料,這樣的來源之一是這樣的:http://feeds.feedburner.com/DiscoveryNews-Top-Stories在這種情況下讀取JSON?

但這源是給我這樣的一些奇怪的JSON數據:

"item": [ 
    { 
    "title": [ 
     "Snazzy Science Photos of the Week (August 10-16)", 
     { 
     "type": "html", 
     "content": "Snazzy Science Photos of the Week (August 10-16)" 
     } 
    ], 
    "description": [ 
     "Glowing rabbits, treasure-hunting badgers and a case of mistaken UFO identity help round out this week&#039;s photos.<img src=\"http://feeds.feedburner.com/~r/DiscoveryNews-Top-Stories/~4/S6Urfvdw2DQ\" height=\"1\" width=\"1\"/>", 
     { 
     "type": "html", 
     "content": "Glowing rabbits, treasure-hunting badgers and a case of mistaken UFO identity help round out this week&#039;s photos." 
     } 
    ], 

目前,我使用下面的代碼來獲得標題的帖子:

if(isset($jit->title->content)){ 
       $title = $decoded_json->query->results->item->title->content; 
      }else{ 
       $title = $decoded_json->query->results->item->title; 
      } 

但是,當我嘗試解析發現新聞feed.Please幫助上面的代碼失敗?

[編輯]: 我使用YQL從source.This獲得相當於JSON是link

+0

我沒有看到任何JSON,只有XML可用。 – Prix

+0

@RajatSaxena你能展示(jsfiddle?)你如何使用YQL/json feed嗎? –

+0

我只是從PHP解析它,我沒有使用javascript.Also,我已經粘貼了我在我的問題中使用的PHP代碼。 –

回答

1

它包裝起來的元素的數組:

"title": [ 
      "No Battery Required for This Wireless Device", 
      { 
       "type": "html", 
       "content": "No Battery Required for This Wireless Device" 
      } 
     ], 

你可以這樣寫的第一個元素:

<?php 
$url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url=%22http://feeds.feedburner.com/DiscoveryNews-Top-Stories%22&format=json&diagnostics=true&callback=cbfunc'; 
$data = substr(file_get_contents($url), 7, -2); 
$json = json_decode($data); 
foreach ($json->query->results->item as $item) 
{ 
    echo "Title: ", $item->title[0], "\nDescription: ", $item->description[0], "\n"; 
    echo "==================================================\n\n"; 
} 

或者使用SimpleXML庫:

$url = 'http://feeds.feedburner.com/DiscoveryNews-Top-Stories?format=xml'; 
$xml = simplexml_load_string(file_get_contents($url)); 
foreach ($xml->channel->item as $item) 
{ 
    echo "Title: ", $item->title, "\nDescription: ", $item->description, "\n"; 
    echo "==================================================\n\n"; 
} 
+0

謝謝,這幫助了很多 –

+0

呵呵,我已經知道如何標記答案是正確的。 –

+0

@RajatSaxena哈哈:P成爲一個習慣張貼我的壞。順便說一下,有一個原因,你不想直接讀取XML? – Prix