Parsing JSON to MySQL table

2020-04-21 06:12发布

问题:

I'm using Zend Framework (1.12) and I'd like to create a table based on a JSON file. I've already created the table and its fields (they're all longtext for now), all it has to do is insert them into the right columns. I followed these examples:

http://www.daniweb.com/web-development/php/threads/381669/json-to-mysql-with-php (second post) Parse JSON to mySQL

The problem is that my JSON is constructed differently (mine has a "root element" called Actie, don't really know the right term) which contains an array with all the objects. Currently, I'm using this code:

$actieurl = "http://creative3s.com/thomas/nmdad/actie.json";
        $my_arr = json_decode(file_get_contents($actieurl));

        $db = new Zend_Db_Adapter_Pdo_Mysql(array(
            'host' => 'localhost',
            'username' => 'root',
            'password' => NULL,
            'dbname' => 'zf-tutorial'
            ));

        foreach($my_arr as $key => $value){
            $sql[] = (is_numeric($value)) ? "`$key` = $value" : "`$key` = '" . mysql_real_escape_string($value) . "'"; 
        }

        $sqlclause = implode(",",$sql);
        $query = "INSERT INTO `testerdetest` SET $sqlclause";
        $db->query($query);

But I'm getting an error saying that I'm passing an array:

Warning: mysql_real_escape_string() expects parameter 1 to be string, array given in C:\Users\Thomas\Documents\GitHub\NMDAD-testing\application\controllers\IndexController.php on line 29

Does anyone know how to solve this with a JSON of this format? Keep in mind that I cannot alter the JSON in any way. Extra links:

JSON: http://creative3s.com/thomas/nmdad/actie.json Table structure: http://i.imgur.com/KtXeEuw.png

回答1:

Your json data has the top level key 'Actie', so you need to be looping through $my_arr->Actie.

You can simplify your code to just:

$actieurl = "http://creative3s.com/thomas/nmdad/actie.json";
$my_arr = json_decode(file_get_contents($actieurl));

$db = new Zend_Db_Adapter_Pdo_Mysql(array(
    'host' => 'localhost',
    'username' => 'root',
    'password' => NULL,
    'dbname' => 'zf-tutorial'
));

foreach($my_arr->Actie as $row){
    $db->insert('testerdetest', (array)$row);
}