php - 使用 PHP 解码多个 JSON URL

标签 php mysql json youtube-api

我正在使用 YouTube API 尝试将来自多个网址的 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());
}
}

最佳答案

$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());
    }
  }
}

关于php - 使用 PHP 解码多个 JSON URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30896646/

相关文章:

mysql - 如何从本地主机Windows(192.168)连接docker子网(172.18)中的mysql?

json - Grails 无法将日期/时间从 JSON 解码回 joda DateTime

php - 如果我不是管理员,如何下载phpBB3论坛的所有帖子?

php - php中的多维数组

php - codeigniter $this->db->query JOIN WHERE 不起作用

c# - 将 Json 与 Web API 和 GET 请求一起使用

ruby-on-rails - Rails 渲染带有驼峰命名法的 json 对象

php - 如何预加载整个网站(例如 Gmail)?

php - 启用 PHP Apache2

mysql - TeSTLink 升级遇到问题 "You need to proceed with Manual upgrade of your DB scheme to DB 1.9.15"