0

我需要一个比如何使用 PHP 从 JSON 中提取数据更简单的解释?而且,我还需要将日期从最终 PHP 中的时间戳中取出。

我可以通过 Wikipedia JSON API 以这种方式获取 PHP 中的“测试文章”元数据:

<?php 
$json_string = file_get_contents("https://en.wikipedia.org/w/api.php?action=query&titles=Test_article&prop=revisions&rvlimit=1&format=json"); 
print $json_string;
?>

这给了我这个:

{"continue":{"rvcontinue":"20161025140129|746140638","continue":"||"},"query":
{"normalized":[{"from":"Test_article","to":"Test article"}],"pages":{"29005947":
{"pageid":29005947,"ns":0,"title":"Test article","revisions":
[{"revid":746140679,"parentid":746140638,"user":"Theblackmidi72",
"timestamp":"2016-10-25T14:01:47Z","comment":"Undid revision 746140638 by
[[Special:Contributions/Theblackmidi72|Theblackmidi72]] ([[User 
talk:Theblackmidi72|talk]])"}]}}}}

但是我如何获取和回显/打印时间戳中的日期,即来自的“2016-10-25” "timestamp":"2016-10-25T14:01:47Z",以及整个 JSON 字符串中的那个字符串?

我假设我需要先抓住完整的字符串016-10-25T14:01:47Z,然后T14:01:47Z从中剥离。

编辑 2016 年 11 月 25 日杰夫的回答效果很好,我将该函数转换为简码,以便将其插入到帖子/页面内容中。

function wikipedia_article_date() {

$url = "https://en.wikipedia.org/w/api.php?action=query&titles=Test_article&prop=revisions&rvlimit=1&format=json";

$data = json_decode(file_get_contents($url), true);
$date = $data['query']['pages']['746140638']['revisions'][0]['timestamp'];

$date = new DateTime($date);
return $date->format('m-d-Y'); 
}

add_shortcode('article_date','wikipedia_article_date');

但现在我收到一个 PHP 警告:

file_get_contents(https://en.wikipedia.org/w/api.php?action=query&
amp;titles=Test_article&amp;prop=revisions&amp;rvlimit=1&amp;format=json):
failed to open stream: no suitable wrapper could be found in 
/functions/shortcodes.php

这是我的简码还是原始功能的问题?

4

1 回答 1

4
  1. json_decode将 JSON 转换为原生 PHP 数组以便于操作。

  2. print_r将递归打印数组,以便您可以轻松地手动读取它以发现文档的结构。

  3. DateTime::format对于转换日期/时间格式很有用。


<?php

$url = "https://en.wikipedia.org/w/api.php?action=query&titles=Test_article&prop=revisions&rvlimit=1&format=json";

$data = json_decode(file_get_contents($url), true);

// this will show you the structure of the data
//print_r($data);

// just the value in which you're interested
$date = $data['query']['pages']['29005947']['revisions'][0]['timestamp'];

// cast to the format you want
$date = new DateTime($date);
echo $date->format('Y-m-d');

2016-10-25

于 2016-11-06T21:35:35.950 回答