我需要一个比How do I extract data from JSON with PHP?更简单的解释而且,我还需要从最后的PHP中的时间戳中剔除日期。使用Wikipedia API获取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]])"}]}}}}
但如何我得到和回声/只打印时间戳的日期,即"timestamp":"2016-10-25T14:01:47Z"
的“2016-10-25”,以及整个JSON字符串中的那个字符串?
我假设我需要先抓住整个字符串016-10-25T14:01:47Z
,然后从中去掉T14:01:47Z
。
编辑11/25/16杰夫的答案很好,我把这个函数转换成了一个简码,所以我可以把它插入到post/page内容中。
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&prop=revisions&rvlimit=1&format=json):
failed to open stream: no suitable wrapper could be found in
/functions/shortcodes.php
这是我的短代码或与原函数的问题?
的[我如何从JSON中提取数据与PHP?(可能的复制http://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) –
尽管你已经说过这个链接的问题不够简单,但它很全面。所有你需要知道的是如何引用对象和数组的元素,例如'$ foo = $ foo_object-> bar'或$ foo = $ foo_array ['bar']'。你可以做的最天真的数据是'$ foo = date('Y-m-d',strtotime($ timestamp));' – moopet