从维基百科api

时间:2017-05-10 07:02:54

标签: php json wikipedia-api data-extraction

我的API响应如下。 我这是为了取消响应。得到了以下的回应。 $data = json_decode($response);

{#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 ▶
      """
  ]
]

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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']);