0

I have this code i am using to write json to a file

<?php
require_once 'vendor/autoload.php';
$faker = Faker\Factory::create();

function getAge($start = 18, $end = 100, $repeat = 20){
    $result = null;
    static $ages = array();
    if ( empty($ages) ) {
        for ($i= $start; $i <= $end; $i++) {
            for($j = 0; $j < $repeat; $j++)
            $ages[] = $i;
        }
    }
    $index = rand(0, count($ages));
    $result = $ages[ $index ];
    unset($ages[ $index ]);
    $ages = array_values($ages);

    return $result;
}

$superstars = array("Adam Cole","Finn Balor","Pete Dunne","Jordan Devlin","Noam Dar");
$fan_favourite_superstar_name = $superstars[ mt_rand( 0, count($superstars) -1 ) ];

$cities = array("London","Manchester","Leeds","Bristol");
$fan_location = $cities[ mt_rand( 0, count($cities) -1 ) ];

$the_models = array("Iphone","Nokia","Huawei","Samsung");
$fan_phone_model = $the_models[ mt_rand( 0, count($the_models) -1 ) ];

for ($x = 1; $x <= 100; $x++) {
    echo $x;
$array = Array (
    "$x" => Array (
        "id" => uniqid(),
        "fan_favourite_superstar_name" => $fan_favourite_superstar_name,
        "fan_location" => $fan_location,
        "fan_phone_model" => $fan_phone_model,
        "fan_name" => $faker->name,
        "fan_age" => getAge(),
        "fan_comments" => $faker->text,
        "fan_picture" => rand(1,500),
        "last_updated" => time() + rand(1,1000),
    )
);

// encode array to json
$json = json_encode(array('fans' => $array));
//write json to file
if (file_put_contents("data.json", $json))
    echo "JSON file created successfully..."."<br/>";
else 
    echo "Oops! Error creating json file...";
}
?>

When i run, only the first line is written. Why are the other lines not being written?.

Gandalf
  • 1
  • 29
  • 94
  • 165
  • Not sure if you set the values in the array properly in the loop, try `$array[$x] = Array ( "id" => uniqid(),` – Nigel Ren Mar 15 '20 at 16:54
  • 1
    You are overwriting the file each time. See [this](https://stackoverflow.com/questions/24972424/create-or-write-append-in-text-file). – El_Vanja Mar 15 '20 at 16:56
  • @El_Vanja You are right, this was missing `if ( file_put_contents('data.json', $json.PHP_EOL , FILE_APPEND | LOCK_EX))` – Gandalf Mar 15 '20 at 17:06
  • If you are appending separate JSON encoded strings to the file, it is no longer a JSON file. – Nigel Ren Mar 15 '20 at 17:12
  • @NigelRen Thats true. I want my json like `{"fans":[{"id":"5e6e601da9a44","fan_favourite_superstar_name":"Pete Dunne","fan_location":"Bristol","fan_gender":"Female","fan_phone_model":"Nokia","fan_name":"Shemar Oberbrunner","fan_age":55,"fan_comments":"Et ","fan_picture":189,"last_updated":1584292832},{"id":"5e6e601da9cc1","fan_favourite_superstar_name":"Pete Dunne","fan_location":"Bristol","fan_gender":"Female","fan_phone_model":"Nokia","fan_name":"Gertrude Wiegand","fan_age":45,"fan_comments":"Repudiandae ","fan_picture":346,"last_updated":1584292326}]}` format – Gandalf Mar 15 '20 at 17:21

1 Answers1

1

You are overwriting the file in each iteration of the loop. You need to tell the file_put_contents function you want to append, like so:

file_put_contents("data.json", $json, FILE_APPEND)

Edit:

Even though this answers the posted question, As Nigel Ren pointed out, this won't create a valid JSON file. Concerning your follow-up comment about the desired format, you'd need to build your array inside the loop and then write once afterwards (by moving everything after $json = json_encode(array('fans' => $array)); outside of the loop).

The correct way to build it is to follow Nigel's first comment about assignment (something the other answers which were deleted in the meantime also dealt with) to avoid overwriting the array each time:

$array["$x"] = Array (
    "id" => uniqid(),
    ...

So, ultimately, you wouldn't even need the appending flag.

E_net4
  • 27,810
  • 13
  • 101
  • 139
El_Vanja
  • 3,660
  • 4
  • 18
  • 21