【问题标题】:Extracting data from Wikipedia API从 Wikipedia API 中提取数据
【发布时间】:2013-06-14 13:05:59
【问题描述】:

我希望能够使用 json 从维基百科中提取标题和描述。所以...维基百科不是我的问题,我是 json 新手,想知道如何使用它。现在我知道有数百个教程,但我已经工作了几个小时,它只是没有显示任何内容,这是我的代码:

<?php
  $url="http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";

    $json = file_get_contents($url);
    $data = json_decode($json, TRUE);

    $pageid = $data->query->pageids;
    echo $data->query->pages->$pageid->title;
?>

只是为了更容易点击:

我知道我可能只是做错了一件小事,但它确实困扰着我,而且代码......我习惯使用 xml,而且我几乎只是进行了切换,所以你能解释一下吗这对我和未来的访客来说有点,因为我很困惑......你需要我没有说的任何东西,只需评论它,我相信我能得到它,并提前谢谢!

【问题讨论】:

  • 将 'jsonfm' 更改为 'json'。
  • html表示链接中只有jsonfm,代码中没有。
  • 啊,是的,你是对的@Joel。我会改变的,谢谢。
  • 哦,我做了jsonfm是为了更容易阅读,doh

标签: php json api wikipedia


【解决方案1】:

$pageid 返回一个包含一个元素的数组。如果你只想拿到第一个,你应该这样做:

$pageid = $data->query->pageids[0];

您可能收到此警告:

 Array to string conversion 

完整代码:

    $url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';

    $json = file_get_contents($url);
    $data = json_decode($json);

    $pageid = $data->query->pageids[0];
    echo $data->query->pages->$pageid->title;

【讨论】:

  • 它是您要从数组中检索的元素的索引。如果数组有 3 个元素 $demo = array('hi', 'my', 'friend'),则 $demo[0] 将是 hi$demo[2] 将是 friend 等。在您的情况下,您不想检索所有数组,但其中包含的唯一元素.这就是您使用[0] 的原因。
  • 感谢您的解释,所以它基本上是按订单获取的...好的,谢谢
【解决方案2】:

我会这样做。它支持在同一个调用中有多个页面。

$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";

$json = file_get_contents($url);
$data = json_decode($json, TRUE);

$titles = array();
foreach ($data['query']['pages'] as $page) {
    $titles[] = $page['title'];
}
var_dump($titles);
/* var_dump returns
array(1) {
  [0]=>
  string(6) "Google"
}
*/

【讨论】:

  • 有帮助,但我只需要一次,+1 努力
【解决方案3】:

试试这个对你有帮助?% 这段代码是在维基百科的 Wikipedia api 的帮助下提取标题和描述

    <?php

       $url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';

       $json = file_get_contents($url);
       $data = json_decode($json);

       $pageid = $data->query->pageids[0];
       $title = $data->query->pages->$pageid->title;
       echo "<b>Title:</b> ".$title."<br>";

       $string=$data->query->pages->$pageid->extract;

       // to short the length of the string 

       $description = mb_strimwidth($string, 0, 322, '...');

       // if you don't want to trim the text use this

           /* 
            echo "<b>Description:</b> ".$string;
           */

        echo "<b>Description:</b> ".$description;
     ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 2014-11-11
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多