Creating JSON File with PHP

Asked

Viewed 4,200 times

0

I’m bringing you BD data that will be used as Values of Keys of my new file.json that I’m trying to create. The Keys are being read from an existing JSON file.

So, basically what I need to do is a file equal to the existing one, however, with different values. The format is more or less like this:

 //Abro arquivo já existente
 $myFile  = fopen($fileName, "r") or die("Unable to open the file !");
 //Content possui o conteúdo do meu arquivo
 $content = json_decode(fread($myFile, filesize($fileName)));
 fclose($myFile); //Fecha arquivo

 foreach( $content as $keys => $value ) {         

    foreach( $value as $key) {
       //....
    }
 }

The format is more or less like this:

{
    "title1": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
     },
     "title2": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"      
     },
} 

With the loop shown above, I can already go through all the Keys of each Title (I don’t know the right name).

I would like help in logic to mount the new file with what I have now.

1 answer

1


You can use the & commercial in foreach (reference), should look like this:

<?php

$json = '{
    "title1": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    },
    "title2": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"      
    }
}';

$decodificado = json_decode($json);

if (!$decodificado) {
    die('JSON invalido');
}

//$title pega o title1 e title2, title3, etc
foreach ($decodificado as $keyTitle => &$title) {

    //$value pega o valor key1, key3, key3, key4, etc
    foreach ($title as $key => &$value) {

        //Aqui um exemplo para alterar as chaves com nome key2 e key3 apenas
        if ($key === 'key2') {
            $value = rand(0, 100);
        } elseif ($key === 'key3') {
            $value = rand(200, 300);
        }
    }
}

print_r($decodificado);

Example in IDEONE: https://ideone.com/sSml1W


Note that if you know exactly what the location of the key is you can simply set the object, for example, assuming you want to change it:

  • Key2 within Title1
  • key1 inside of title2
  • key3 inside of title2

Then you must do so:

<?php

$json = '{
    "title1": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    },
    "title2": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"      
    }
}';

$decodificado = json_decode($json);

if (!$decodificado) {
    die('JSON invalido');
}

$decodificado->title1->key2 = 'Novo valor FOO';
$decodificado->title2->key1 = 'Novo valor BAR';
$decodificado->title2->key3 = 'Novo valor BAZ';

print_r($decodificado);

Example in IDEONE: https://ideone.com/bvFxkV


So knowing the name of the keys you want to change later just use the json_encode and save again to a file (or wherever you want), for example:

...

$codificado = json_encode($decodificado);

file_put_contents('novo.json', $codificado);
  • Show. Can you identify if the next iteration in the loop will exist or not ? Working with Json I couldn’t access any kind of index, only the key values.

  • @Playhardgopro in the loop I created the var $keyTitle concerning Title1, title2, etc and var $key I created it to detect if it’s key1, Key2, etc., so you can know exactly what key it’s in and change it as needed, assuming you want to change the key53 that is inside the title22 just make a if so if ($keyTitle == 'title22' && $key == 'key52') { $value = 'NOVO VALOR'; }, then the trick is to use Ifs ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.