I
I
imagance2021-12-14 06:27:49
PHP
imagance, 2021-12-14 06:27:49

Why does JSON decoding return null?

json decoding returns null. I tried to convert to utf8 but it did not help, I used all the options that are possible. json_last_error() returns 4. Please help.

$str = file_get_contents("data.json");
$file = json_decode($str);
var_dump($file);

{"login":"igor","password":"qwerty"}
{"login":"igor","password":"qwerty"}
{"login":"igor","password":"qwerty"}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Andreichenko, 2021-12-14
@imagance

Not valid json, multiple root elements.

[
   {
      "login":"igor",
      "password":"qwerty"
   },
   {
      "login":"igor",
      "password":"qwerty"
   },
   {
      "login":"igor",
      "password":"qwerty"
   }
]

N
Nadim Zakirov, 2021-12-14
@zkrvndm

First, read your file line by line, and only then decode these lines in a loop:

<?php

// Показ ошибок:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Кодировка документа для браузера:
header('Content-Type: text/plain; charset=UTF-8');

$arr = file('data.json'); // Читаем файл в массив построчно

// Раскодируем строки как JSON и записываем обратно в массив:

foreach ($arr as &$val) {
    $val = json_decode($val,  true);
}


print_r($arr); // Выводим результат

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question