2015-06-17 36 views
0

我使用YouTube API嘗試將來自多個URL的JSON數據放入mySQL數據庫。我試圖在多個JSON鏈接上使用json解碼器,此刻我的代碼刪除了第一個數組,並用第二個數組覆蓋它。請注意,我不想使用array_merge函數,因爲我想使用大約6-7個json URL。如果你可能非常具體,那也會很棒,因爲我對PHP很陌生。使用PHP解碼多個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()); 
} 
} 
+0

如果可以的話,你應該[停止使用'mysql_ *'功能(http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in -php)。他們不再被維護,並[正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。瞭解[準備](http://en.wikipedia.org/wiki/Prepared_statement)[聲明](http://php.net/manual/en/pdo.prepared-statements.php),並考慮使用PDO ,[這真的不難](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+0

爲什麼不將鏈接放入數組中,然後將JSON處理代碼放入單獨的函數中並針對每個URL調用它。 – theduck

回答

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

謝謝,雖然我收到此錯誤...「不能使用stdClass類型的對象作爲數組。」我猜這是與「真實」部分沒有包含在一起的事情? – user3599895

+0

是的,添加'true'作爲json_decode – theduck

+0

的第二個參數哦,對不起,我忘了。 – edwardbrosens