我正在尝试解码两个不同的json提要网址并合并成一个输出/输出。但是,我已经尝试了以下方法,但运气并不好。
feed source 1: http://sourcesample.com/feed/posts
data: [
{
name: "Me",
url: "http://example.com/sample",
title: "Sample Title",
}
]
feed source 2: http://differentsource.com/feed/details
data: [
{
likes: "200",
shares: "300",
total: "1000",
}
]
$sources =array("http://sourcesample.com/feed/posts", "http://differentsource.com/feed/details");
$requests = file_get_contents($sources[0],$sources[1]);
$response = json_decode($requests);
foreach($response->data as $item){
echo'<li>'.$item->name.'</li><li>'.$item->shares.'</li>'
打印名称有效,但在尝试打印第二个对象进纸时,没有任何内容。有什么想法吗?
file_get_contents()
一次不会返回多个URL的内容。第二个参数被视为true
,大致为use_include_path
参数。为了您的目的,这无关紧要。
无论如何,只读取第一个提要。它不包括"共享"数据。
即使两者都被读取,结果也将是:
'data: [
{
name: "Me",
url: "http://example.com/sample",
title: "Sample Title",
}
]
data: [
{
likes: "200",
shares: "300",
total: "1000",
}
]'
这不是一个有效的 JSON 字符串 - 它是两个彼此相邻的对象,而不是合并。
如果您真的确信两个提要的大小相同,则可以(分别)读取它们,然后一次遍历它们:
$names = json_decode( file_get_contents( $sources[0] ) );
$stats = json_decode( file_get_contents( $sources[1] ) );
for ( $i = 0; $i < count( $names->data ); ++$i )
{
$name = $names->data[$i];
$stat = $stats->data[$i];
echo '<li>' . htmlspecialchars($name->name) . '</li><li>' .
htmlspecialchars($stat->shares) . '</li>';
}