試圖從API存儲一些json數據到MySQL。將json內容從API存儲到mysql數據庫
我用這簡單的PHP代碼
<?php
require 'config.php';
$url = "https://www.widgety.co.uk/api/operators.json?app_id<key>&token<token>";
$string = file_get_contents('https://www.widgety.co.uk/api/operators.json?app_id<key>&token=<token>');
$arr = json_decode($string, true);
foreach($arr as $item){
$title = $item['operator']['title'];
$id = $item['operator']['id'];
$profile_image = $item['operator']['profile_image_href'];
$cover_image = $item['operator']['cover_image_href'];
$href = $item['operator']['href'];
$html_href = $item['operator']['html_href'];
$unique_text = $item['operator']['unique_text'];
$reasons_to_book = $item['operator']['reasons_to book'];
$members = $item['operator']['members_club'];
$brochures = $item['operator']['brochures'];
$ships = $item['operator']['ships'];
$video_url = $item['operator']['video_url'];
$query("INSERT INTO operator (title, id, profile_image) VALUES('$title', '$id', '$profile_image')");
$dataatodb = mysqli_query($con, $query);
if(!$dataatodb){
die("Error" . mysqli_error($con));
}
}
?>
但我得到這個錯誤
Warning: file_get_contents(app_id<key>&token<token>): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in C:\xampp\htdocs\mypage\dataload.php on line 6
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\mypage\dataload.php on line 9
我在做什麼錯?
PS網址]我有權利APP_ID和令牌
您的代碼容易受到SQL注入。請學習使用[預先準備的語句](https://www.youtube.com/watch?v=nLinqtCfhKY)。 –
使用CURL而不是'file_get_contents'出於安全原因,大多數生產環境不允許使用'file_get_contents'。 –
您是否在全新的瀏覽器會話中嘗試了生成的URL以查看生成的URL是否正常工作?你是否檢查過你的PHP安裝[配置爲允許打開url](http://us2.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen)? –