2016-11-06 58 views
0

我需要一个比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&amp;prop=revisions&amp;rvlimit=1&amp;format=json): 
failed to open stream: no suitable wrapper could be found in 
/functions/shortcodes.php 

这是我的短代码或与原函数的问题?

+2

的[我如何从JSON中提取数据与PHP?(可能的复制http://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) –

+0

尽管你已经说过这个链接的问题不够简单,但它很全面。所有你需要知道的是如何引用对象和数组的元素,例如'$ foo = $ foo_object-> bar'或$ foo = $ foo_array ['bar']'。你可以做的最天真的数据是'$ foo = date('Y-m-d',strtotime($ timestamp));' – moopet

回答

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日

+0

谢谢,这很好。数据如何被抓取以及我使用print_r来查看数组很有趣。还有PHP功能来更改日期格式。这也适用于不同的页面,只要我还可以在$ data行中查找并更改页面标识(通过在数组中查找页面标识)以及$ url中的页面标题。 – BlueDogRanch

+0

这仍然很好,但我又迈出了一步,并把它变成了一个简码。但是现在我得到了一个PHP警告,我知道这并不严重,但我希望能够适应它;我编辑了我的问题。 – BlueDogRanch