JSON文件到数组

时间:2018-10-15 18:10:13

标签: php json

在将其标记为重复之前,我可能已经尝试过StackOverflow上的每个相关问题,但似乎没有任何作用。

我有一个很大的JSON文件(8112行),我试图将其转换为数组,然后将数据输入数据库。到目前为止,我什至无法将JSON转换成数组。

file.json

[
   {
      "artistname":"1 Wild Night1",
      "publicistName":"Amy Sciarretto",
      "publicistEmail":"amy@amysciarretto.com",
      "id":"306",
      "updated":"2018-02-13 07:23:19",
      "website":"",
      "outdated":"danger",
      "contactid":"175"
   },
   {
      "artistname":"2Cellos",
      "publicistName":"Angela Barkan",
      "publicistEmail":"angela.barkan@sonymusic.com",
      "id":"404",
      "updated":"2015-03-11 05:05:12",
      "website":"",
      "outdated":"danger",
      "contactid":"192"
   },
   {
      "artistname":"3 Doors Down",
      "publicistName":"Taylor Vaughn",
      "publicistEmail":"Taylor.Vaughn@umusic.com",
      "id":"760",
      "updated":"2016-03-04 09:32:06",
      "website":"",
      "outdated":"danger",
      "contactid":"205"
   },

这里有3个条目,但下面还有很多条目。我不完全确定有多少。

file.php

$arr = json_decode($json, true);

var_dump($arr); // response is NULL

if (is_array($json)) {
foreach($json as $data) {
  echo $data['artistname'];
  echo $data['publicistName'];
  echo $data['publicistEmail'];
}
} else {
  echo "not an array"; // this is the response for the if statement
}

我在做什么错了?

此外,我已经在JSONLint和其他服务之一上测试了整个JSON文件,根据它们的说法,它是完全有效的。

1 个答案:

答案 0 :(得分:-1)

S。得到它的工作。如果有人需要,这是工作代码。谢谢大家。

$json = file_get_contents('publicists.json');
$data = json_decode($json);
foreach ( $data as $pub ) {
    $artist = $pub->artistname;
    $publicist = $pub->publicistName;
    $email = $pub->publicistEmail;
    $updated = $pub->updated;

    try
        {
      $sqlInsert = "INSERT INTO publicists(artist, publicist, email, updated)
    VALUES (:artist, :publicist, :email, :updated)";

      //use PDO prepared to sanitize data
      $statement = $db->prepare($sqlInsert);

      //add the data into the database
      $statement->execute(array(':artist' => $artist, ':publicist' => $publicist, ':email' => $email, ':updated' => $updated));

  }catch (PDOException $ex){
    $result = $ex->getMessage();
  }
}