Import JSON file into MYSQL database with php

2020-02-29 11:31发布

问题:

i'am trying to insert a JSON file into my MYSQL Database. But only the second line is inserted every time i run this script. along whit a bunch of errors for "Invalid argument supplied for foreach()"

I got this script from another webpage but i can't get it work smooth! Someone how can help me out?

php script:

<?php
$con = mysql_connect("localhost","***","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***", $con);



$f = file_get_contents('http://.../data.json');
$arr = explode('},',$f);  // Prepare for json_decode BUT last } missing
$global_arr = array(); // Contains each decoded json (TABLE ROW)
$global_keys = array(); // Contains columns for SQL

if(!function_exists('json_decode')) die('Your host does not support json');
for($i=0; $i<count($arr); $i++)
{
    $decoded = json_decode($arr[$i].'}',true); // Reappend last } or it will return NULL
    $global_arr[] = $decoded;
    foreach($decoded as $key=> $value)
    {
    $global_keys[$key] = '';
    }
}

// iterate $global_arr
for($i=0; $i<count($global_arr); $i++) // this is faster than foreach
{
// NOW use what ardav suggested
    foreach($global_arr[$i] as $key => $value){
    $sql[] = (is_numeric($value)) ? "`$key` = $value" : "`$key` = '" . mysql_real_escape_string($value) . "'";
    }
    $sqlclause = implode(",",$sql);
    $rs = mysql_query("INSERT INTO temp_table SET $sqlclause");
} // for i
//

?>

the errors:

Warning: Invalid argument supplied for foreach() in ***.php on line 21

Warning: Invalid argument supplied for foreach() in ***.php on line 21

Warning: Invalid argument supplied for foreach() in ***.php on line 31

Warning: implode() [function.implode]: Invalid arguments passed in ***.php on line 34

Warning: Invalid argument supplied for foreach() in ***.php on line 31

Json file:

{
   "data": [
      {
         "name": "name freiend 1",
         "id": "friend id 1"
      },
      {
         "name": "name freiend 2",
         "id": "friend id 2"
      },
      {
         "name": "name freiend 3",
         "id": "friend id 3"
      }
         ],
   "paging": {
      "next": "https://graph.facebook.com/100002295143005/friends?access_token=***"
   }
}

回答1:

Try parsing the entire JSON file instead of one part, and with fewer loops:

$f = file_get_contents('http://.../data.json');

if(!function_exists('json_decode')) die('Your host does not support json');
$feed = json_decode($f);
for($i=0; $i<count($feed['data']); $i++)
{
    $sql = array();
    foreach($feed['data'][$i] as $key => $value){
        $sql[] = (is_numeric($value)) ? "`$key` = $value" : "`$key` = '" . mysql_real_escape_string($value) . "'";
    }
    $sqlclause = implode(",",$sql);
    $rs = mysql_query("INSERT INTO temp_table SET $sqlclause");
}