使用php将JSON文件导入MYSQL数据库

时间:2012-08-28 18:40:55

标签: php mysql json import

我试图将JSON文件插入到我的MYSQL数据库中。 但每次运行此脚本时,只插入第二行。为“为foreach()提供的无效参数”中的一堆错误

我从另一个网页上获得了这个脚本,但是我无法让它顺利运行! 有人怎么能帮帮我?

php脚本:

<?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
//

?>

错误:

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文件:

{
   "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 个答案:

答案 0 :(得分:-1)

尝试解析整个JSON文件而不是一个部分,并使用更少的循环:

$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");
}