2017-05-10 59 views
0

我有如下的API響應。 我這是爲了解決這個問題。並得到低於迴應。 $data = json_decode($response);從維基百科api中提取具體數據

{#240 ▼ 
    +"batchcomplete": "" 
    +"query": {#243 ▼ 
    +"pages": {#234 ▼ 
     +"171166": {#245 ▼ 
     +"pageid": 171166 
     +"ns": 0 
     +"title": "Nepal" 
     +"extract": """ 
      Nepal (/nəˈpɔːl/; Nepali: नेपाल Nepāl [neˈpal]), officially the Federal Democratic Republic of Nepal (Nepali: सङ्घीय लोकतान्त्रिक गणतन्त्र नेपाल Sanghiya Loktā ▶ 
      The territory of Nepal has a recorded history since the Neolithic age. The name "Nepal" is first recorded in texts from the Vedic Age, the era which founded Hin ▶ 
      Modern Nepal is a federal secular parliamentary republic. It has seven states. Nepal is a developing nation, ranking 144th on the Human Development Index (HDI) ▶ 
      Nepal's foreign relations expanded after the Anglo-Nepal Treaty of 1923, which was recognized by the League of Nations. After a Soviet veto in 1949, Nepal was a ▶ 
      """ 
     } 
    } 
    } 
} 

我想提取titlecontent。我該怎麼做?

編輯:我曾嘗試$data = json_decode($response, true);,並通過這樣var_dump($data['query']['pages'])得到下面的結果。結果:

array:1 [▼ 
    171166 => array:4 [▼ 
    "pageid" => 171166 
    "ns" => 0 
    "title" => "Nepal" 
    "extract" => """ 
     Nepal (/nəˈpɔːl/; Nepali: नेपाल Nepāl [neˈpal]), officially the Federal Democratic Republic of Nepal (Nepali: सङ्घीय लोकतान्त्रिक गणतन्त्र नेपाल Sanghiya Loktā ▶ 
     The territory of Nepal has a recorded history since the Neolithic age. The name "Nepal" is first recorded in texts from the Vedic Age, the era which founded Hin ▶ 
     Modern Nepal is a federal secular parliamentary republic. It has seven states. Nepal is a developing nation, ranking 144th on the Human Development Index (HDI) ▶ 
     Nepal's foreign relations expanded after the Anglo-Nepal Treaty of 1923, which was recognized by the League of Nations. After a Soviet veto in 1949, Nepal was a ▶ 
     """ 
    ] 
] 
+0

刪除圖像和粘貼代碼.... –

+0

https://stackoverflow.com/questions/7185288/how-to-get-wikipedia-content-using-wikipedias-api –

+0

它沒有回答我的問題@Ahmad。 – vijayrana

回答

0

只需使用頁面作爲數組:

$response = json_decode(file_get_contents('https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow')); 

$pages = (array) $response ->query->pages; 
foreach ($pages as $id => $page) { 
    echo $page->title; 
} 
+0

。謝謝 – vijayrana

0

使用formatversion=2獲得在好辦了格式的數據。

$response = json_decode(file_get_contents('https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&formatversion=2&exintro=&titles=Stack%20Overflow'), true); 
echo($response['query']['pages'][0]['title']);