尝试从API将一些json数据存储到MySQL。
我正在使用这个简单的PHP代码
NSArray
但是我收到了这个错误
<?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));
}
}
?>
我做错了什么?
PS在网址上我有正确的app_id和令牌
答案 0 :(得分:1)
当你的foreach ($jsonObject as $item) {
$title = $item->title;
}
数组是一个对象时,你正在对它进行处理。
->
注意['']
而不是var_dump()
要进一步调试,请使用$apiURL = 'url';
$response = file_get_contents($apiUrl);
$jsonResponse = json_decode($response);
var_dump($jsonResponse);
检查您的变量是否包含实际对象,或者您的api请求是否失败。
var maxValue = 50, minValue = 1;
var yourArray = []; // You can have your numbers array in this one.
var sortedArray = yourArray.sort(); // this will sort the array
var resultArray = myarray.filter(function(value){
return (value > minValue && value < maxValue);
});
答案 1 :(得分:1)
/* create a connection */
$mysqli = new mysqli("localhost", "root", null, "yourDatabase");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* let's say we're grabbing this from an HTTP GET or HTTP POST variable called jsonGiven... */
$jsonString = $_REQUEST['jsonGiven'];
/* but for the sake of an example let's just set the string here */
$jsonString = '{"name":"jack","school":"colorado state","city":"NJ","id":null}
';
/* use json_decode to create an array from json */
$jsonArray = json_decode($jsonString, true);
/* create a prepared statement */
if ($stmt = $mysqli->prepare('INSERT INTO testdemo (name, school, city, id) VALUES (?,?,?,?)')) {
/* bind parameters for markers */
$stmt->bind_param("ssss", $jsonArray['name'], $jsonArray['school'], $jsonArray['city'], $jsonArray['id']);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();