-1

我在文本文件中有一些 JSON 格式的数据,如下所示。我需要使用 php 将此数据插入 mysql 但不能这样做。

{"address":"+92 334 6629424","service_center":"Test Sending Sms","id":3,"locked":0,"person":0,"protocol":0,"read":0,"reply_path_present":2,"seen":0,"error_code":0,"status":1,"date":1873326412,"thread_id":1,"type":-1}

我的 PHP 文件有这样的代码。

<?php $source_file  = "SMS2012-05-21.txt"; $handle = fopen("SMS2012-05-21.txt", "r");
$col_names = implode(",", fgetcsv($handle)); // Getting comma separated list of col name

 $link = mysql_connect('localhost', 'root', '');
 mysql_select_db("messages");
 while (($data = fgetcsv($handle)) !== FALSE) {
 $values = "";
 foreach($data as $key => $value) {
     if ($key != 0) $values .= ", ";
     $values .= "'".mysql_escape_string($value)."'";
 }
 mysql_query('INSERT INTO messages ('.$col_names.') VALUES ('.$values.')');
 }
 ?>

我找不到任何结果或任何错误。任何人都可以在这方面帮助我,我错了?

4

2 回答 2

1

您应该使用json_decode函数来操作 json 数据。

<?php


  $source_file  = "SMS2012-05-21.txt";
  $string = file_get_contents($source_file);
  $json = json_decode($string,true);

  //DB Conn Handling Stuff

  $cols = array(); $values = array();

  foreach($json as $key=>$value)
  {
      array_push($cols,'`' . $key . '`');
      if(is_string($value))
      {
         array_push($values,'\''.$value.'\'');
      }
      else
      {
         array_push ($values, $value);
      }
  }

  $col_name = implode(',',$cols);
  $col_value = implode(',',$values);

  $query = 'INSERT INTO messages('.$col_name.') VALUES ('.$col_value.')';
  mysql_query($query,$connection) or die(echo mysql_error());      

?>
于 2012-05-24T15:03:43.497 回答
0

也许我错过了一些东西,你应该这样使用它:

<?php $source_file  = "SMS2012-05-21.txt"; 
$handle = fopen("SMS2012-05-21.txt", "r");
$data = fread($handle, filesize($source_file));
$jsonArray = json_decode($data, true);

$keys = implode(',', array_keys($jsonArray));
$values = "'" . implode("','", $jsonArray) . "'";

$link = mysql_connect('localhost', 'root', '');
mysql_select_db("messages");

mysql_query('INSERT INTO messages ('.$keys.') VALUES ('.$values.')');
于 2012-05-24T14:25:42.507 回答