我正在从另一台服务器获取json数据,并且需要将thouse数据保存在mysql中。我尝试了这段代码,但是存在问题 当我运行此代码时,我得到:每个值的字符串偏移量非法。 我希望我能说清楚什么,如果我没有解释,请告诉我。
<?php
require('db.php');
$url = 'xxxxx';
$data =json_encode(array('xxx' => 'xxxx',
'xxxx' => 'xxxxx',
'xxxx' =>'xxxx',
'xxxx' =>'xxxx',
'xxxx' =>'xxxx')
);
$options = array(
'http' => array(
'header' => "Content-type: application/json",
'method' => 'POST',
'content' => $data
)
);
$context= stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { }
echo $result ;
foreach ((array)$result as $row) {
$table="INSERT INTO table_name(xxx,xxx,xx,xxx,xx,xxx,xxx,xxxx,xxx)
VALUES('".$row["xxxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxxx"]."')";
if ($conn->query($table ) === TRUE) {
echo "Record added Successfully<br>";
}
else
{
echo "Error: " . $insert_value . "<br>" . $con->error;
}
}
?>
答案 0 :(得分:0)
在有else
条件的情况下,也应该有if
语句,以防有结果。结果应该在else
中解析。
代码应为:
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo "Error in fetching records.";
} else {
echo $result;
$rows = (array) $result;
foreach ($rows as $row) {
$table = "INSERT INTO table_name(xxx,xxx,xx,xxx,xx,xxx,xxx,xxxx,xxx)
VALUES('" . $row["xxxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxxx"] . "')";
if ($conn->query($table) === TRUE) {
echo "Record added Successfully<br>";
} else {
echo "Error: " . $insert_value . "<br>" . $con->error;
}
}
}