获取文章时间戳在PHP与维基百科的API


Get article timestamp in PHP with Wikipedia API

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

我可以通过维基百科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]])"}]}}}}

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

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

Jeff的回答很好,我把这个函数转换成一个短代码,这样我就可以把它插入到帖子/页面内容中。

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

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

  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