如何向Mysql添加多个JSON数据链接

时间:2015-04-27 08:58:09

标签: mysql json

我有很多内部有JSON数据的链接,我需要链接到mysql的数据,这可能是最快的方法吗?

是否可以修改下面的代码,使其能够从多个网址中读取?

<?php
    //connect to mysql db
    $con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
    //connect to the employee database
    mysql_select_db("employee", $con);

    //read the json file contents
    $jsondata = file_get_contents('empdetails.json');

    //convert json object to php associative array
    $data = json_decode($jsondata, true);

    //get the employee details
    $id = $data['empid'];
    $name = $data['personal']['name'];
    $gender = $data['personal']['gender'];
    $age = $data['personal']['age'];
    $streetaddress = $data['personal']['address']['streetaddress'];
    $city = $data['personal']['address']['city'];
    $state = $data['personal']['address']['state'];
    $postalcode = $data['personal']['address']['postalcode'];
    $designation = $data['profile']['designation'];
    $department = $data['profile']['department'];

    //insert into mysql table
    $sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddress, city, state, postalcode, designation, department)
    VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city', '$state', '$postalcode', '$designation', '$department')";
    if(!mysql_query($sql,$con))
    {
        die('Error : ' . mysql_error());
    }
?>

1 个答案:

答案 0 :(得分:0)

以下是从excel文件中读取网址的示例。

我正在使用http://code.google.com/p/php-excel-reader/

文件 - urls.xls。

假设此excel在第一列中包含url。

<?php
//connect to mysql db
$con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
//connect to the employee database
mysql_select_db("employee", $con);

$data = new Spreadsheet_Excel_Reader("urls.xls",false);
$rows = $data->rowcount(0);

for( $i=0;$i<$rows;$i++ ) {
    //read the json file contents
    $jsondata = file_get_contents($data->val($i,0));

    //convert json object to php associative array
    $data = json_decode($jsondata, true);

    //get the employee details
    $id = $data['empid'];
    $name = $data['personal']['name'];
    $gender = $data['personal']['gender'];
    $age = $data['personal']['age'];
    $streetaddress = $data['personal']['address']['streetaddress'];
    $city = $data['personal']['address']['city'];
    $state = $data['personal']['address']['state'];
    $postalcode = $data['personal']['address']['postalcode'];
    $designation = $data['profile']['designation'];
    $department = $data['profile']['department'];

    //insert into mysql table
    $sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddress, city, state, postalcode, designation, department)
    VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city', '$state', '$postalcode', '$designation', '$department')";
    if(!mysql_query($sql,$con))
    {
        die('Error : ' . mysql_error());
    }
}
?>

希望这有帮助。