I have a JSON that looks like this:
{
"num_found": 407343,
"results": [
{
"speaker_state": "LA",
"speaking": [
"ABC",
"DEF",
"GHI"
],
"speaker_party": "D",
},
And so on. I am trying to parse this data into a MySQL database. I adapted the following php code:
<?php
$hostname_ndb = "localhost";
$database_ndb = "senate";
$username_ndb = "root";
$password_ndb = "root";
$ndb = mysql_pconnect($hostname_ndb, $username_ndb, $password_ndb) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_ndb);
$url = "http://xxx.yyy/text.json";
$json = file_get_contents($url);
$out = json_decode($json, true);
foreach($out["results"] as $results) {
$speaker_state = $results['speaker_state'];
$speaking2 = $results['speaking'];
$speaking = implode('', $speaking2);
$date = $results['date'];
mysql_query("INSERT INTO speeches (speaker_state, speaking, date ) VALUES('$speaker_state', '$speaking','$date')") or die (mysql_error());
}
?>
There is an array within an array and it seems to be the problem. The script does not work, data is not stored in the database. The script returns the error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'speaking, date, ' at line 1.
The PHP log shows a notice:"PHP Notice: Array to string conversion in /Applications/MAMP/htdocs/json.php on line 46" in the php log.
var_dump($speaking2) returns:
array(3) { [0]=> string(713) "XXX" [1]=> string(891) "ZZZ" [2]=> string(1189)
and so on. How would you advise me to adapt this script to make it work?