检查此代码可能会对您有所帮助:
1 在 PHP 中读取 JSON 文件:
PHP supports the function file_get_contents() which will read the entire file and returns it as a string.
//read the json file contents
$jsondata = file_get_contents('yourjsonfilename.json');
2 将 JSON 字符串转换为 PHP 数组:
//convert json object to php associative array
$data = json_decode($jsondata, true);
The first parameter $jsondata contains the JSON file contents. The second parameter true will convert the string into PHP associative array.
3 解析 PHP 数组值并存储在变量中:
//get the details
$id = $data['Id'];
$name = $data['personal']['name'];
$age = $data['personal']['age'];
$streetaddress = $data['personal']['address']['streetaddress'];
$city = $data['personal']['address']['city'];
$state = $data['personal']['address']['state'];
$postalcode = $data['personal']['address']['postalcode'];
4 使用 PHP 代码将 JSON 插入 MySQL 数据库现在我们将插入
使用以下查询将 JSON 对象值提取到 MySQL 表中。
//insert into mysql table
$sql = "INSERT INTO tbl_students(studentId, name, age, streetaddress, city, state, postalcode)
VALUES('$id', '$name', '$age', '$streetaddress', '$city', '$state', '$postalcode')";
if(!mysqli_query($con, $sql))
{
die('Error : ' . mysql_error());
}
现在我们已经成功将 JSON 数据导入 MySQL 数据库,如下所示:
{
"Id": "ST001",
"personal": {
"name": "John Smith",
"age": "29",
"address": {
"streetaddress": "5 14th Street",
"city": "New York",
"state": "NY",
"postalcode": "12548"
}
}
}
另一种方式是:
<?php
$josndata = '{
"student":{ "name":"Harry", "country":"United State", "ContactNo":2545454 }
}';
// Database connection
$conn = new mysqli('localhost', 'username', 'password', 'databasename');
// Insert data Query
$sql = "INSERT INTO student_table ( name, jsondata )
VALUES ('Harry', '$josndata')";
if ($conn->query($sql) === TRUE) {
echo "Insert your JSON record successfully";
}
?>