Reading JSON file - Attempt to read property on null

This public forum is for user-to-user discussions of PHPMaker. Note that this is not support forum.
Post Reply
nabilahasna
User
Posts: 221
Contact:

Reading JSON file - Attempt to read property on null

Post by nabilahasna »

Hi

I Have json file with this structure

[{"tahun":2024,"kd_klp":"K4","kd":"112109","alamat":"Jl. Jenderal Sudirman , Bandung"},
{"tahun":2024,"kd_klp":"K4","kd":"112109","alamat":"Jl. Jenderal Sudirman , Bandung"},
{"tahun":2024,"kd_klp":"K4","kd":"112109","alamat":"Jl. Jenderal Sudirman , Bandung"}]

then i try to save json data in database with custom file impor.php

<?php
 

$dbhost = "localhost";
$dbuser = "u1549977";
$dbpass = "n4b1l4h4";
$dbname = "u1549977_moon";
 

$url = "http://localhost/kontra.json";
$json = file_get_contents($url);
 

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
 

$split = explode("\n", $json);
 

foreach ($split as $baris) {

    $data = json_decode($baris);
    $tahun = $data->tahun;
    $kd_klp = $data->kd_klp;
    $kd = $data->kd;
    $alamat = $data->alamat;
     
    


    $query = "INSERT INTO apnon VALUES ('$tahun','$kd_klp','$kd','$alamat')";
 
    $result = mysqli_query($conn, $query);
}
 
echo "Import Done !!";
 

mysqli_close($conn);
?>

but error show like this :

Warning: Attempt to read property "tahun" on null in C:\xampp\htdocs\views\Impor.php on line 33
Warning: Attempt to read property "kd_klp" on null in C:\xampp\htdocs\views\Impor.php on line 34
Warning: Attempt to read property "kd" on null in C:\xampp\htdocs\views\Impor.php on line 35
Warning: Attempt to read property "alamat" on null in C:\xampp\htdocs\views\Impo.php on line 36

How to solve that problem? any advice?
Thank You


arbei
User
Posts: 9384

Post by arbei »

You should simply use json_decode($json) to get the array directly.


nabilahasna
User
Posts: 221
Contact:

Post by nabilahasna »

I try this :

$split = explode("\n", $json);
 
    $data = json_decode($json);
    $tahun = $data->tahun;
    $kd_klp = $data->kd_klp;
    $kd = $data->kd;
    $alamat = $data->alamat;
     
    $query = "INSERT INTO apnon VALUES ('$tahun','$kd_klp','$kd','$alamat')";
 
    $result = mysqli_query($conn, $query);

same problem show :
Warning: Attempt to read property "tahun" on array in C:\xampp\htdocs\views\Impor.php on line 33
Warning: Attempt to read property "kd_klp" on array in C:\xampp\htdocs\views\Impor.php on line 34
Warning: Attempt to read property "kd" on array in C:\xampp\htdocs\views\Impor.php on line 35
Warning: Attempt to read property "alamat" on array in C:\xampp\htdocs\views\Impor.php on line 36

any idea?
Thank You


arbei
User
Posts: 9384

Post by arbei »

arbei wrote:

You should simply use json_decode($json) to get the array directly.


Post Reply