【问题标题】:Decoding multiple JSON URL's using PHP使用 PHP 解码多个 JSON URL
【发布时间】:2015-09-02 23:41:42
【问题描述】:

我正在使用 YouTube API 尝试将来自多个 URL 的 JSON 数据放入 mySQL 数据库。我正在尝试在多个 JSON 链接上使用 json 解码器,目前我的代码删除了第一个数组并用第二个数组覆盖它。请注意,我不想使用 array_merge 函数,因为我想使用大约 6-7 个 json URL。如果您可以非常具体,那也很棒,因为我对 php 很陌生。

$linkone = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId={playlistID}&key={Key}';
$linktwo = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId={PlaylistID}&key={Key}';


$content = file_get_contents($linkone);
$content2 = file_get_contents($linktwo);

$json = json_decode($content, true);


foreach($json['items'] as $row)
{
$title = $row['snippet']['title'];
$title = mysql_real_escape_string($title);
$description = $row['snippet']['description'];
$description = mysql_real_escape_string($description);

$publishedAt = $row['snippet']['publishedAt'];
$publishedAt = mysql_real_escape_string($publishedAt);
$high = $row['snippet']['thumbnails']['high']['url'];
$high = mysql_real_escape_string($high);

$sql = "INSERT INTO table(title, description, publishedAt, high) VALUES('".$title."','".$description."','".$publishedAt."','".$high."')";

if(!mysql_query($sql,$conn))
{
die('Error : ' . mysql_error());
}
}

【问题讨论】:

标签: php mysql json youtube-api


【解决方案1】:
$linkone = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId={playlistID}&key={Key}';
$linktwo = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId={PlaylistID}&key={Key}';

$jsonArray = array(
  json_decode(file_get_contents($linkone)),
  json_decode(file_get_contents($linktwo))
);

foreach($jsonArray as $json) {
  foreach($json['items'] as $row)
  {
    $title = $row['snippet']['title'];
    $title = mysql_real_escape_string($title);
    $description = $row['snippet']['description'];
    $description = mysql_real_escape_string($description);

    $publishedAt = $row['snippet']['publishedAt'];
    $publishedAt = mysql_real_escape_string($publishedAt);
    $high = $row['snippet']['thumbnails']['high']['url'];
    $high = mysql_real_escape_string($high);

    $sql = "INSERT INTO table(title, description, publishedAt, high)
      VALUES('".$title."','".$description."','".$publishedAt."','".$high."')";

    if(!mysql_query($sql,$conn))
    {
      die('Error : ' . mysql_error());
    }
  }
}

【讨论】:

  • 谢谢,虽然我收到了这个错误...“不能使用 stdClass 类型的对象作为数组。”我猜这与不包括“真实”部分有关?
  • 是的,在json_decode中添加true作为第二个参数
  • 哦,是的,对不起,我忘了。
猜你喜欢
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多