I am trying to generate JSON using PHP, and I'm having some issues. I need to iterate through all the images in a folder, and post the json to an API. I'm almost there, but JSON not formatting correctly.

What I want to acheive is this

{
    "md": {
        "title": "Title"
    },
    "pageList": {
        "pages": [
            {
                "fileName": "001.jpg",
                "pageNr": 1
            },
            {
                "fileName": "002.jpg",
                "pageNr": 2
            }
        ]
    }
}

and so on for each page.

I am almost there, but it is not formatting correctly, and I am getting \n newline characters in my output:

Here's my code:

<?php

function json_generate() {
    $title="Title";
    // on my system: produces an array of files in a directory (working correctly)
    // $files = array_diff(scandir(__DIR__ . "/images"), array('.', '..'));
    //
    // below code for testing:
    $files = array('001.jpg','002.jpg');
    $files_array = array();
    foreach($files as $file) {
        $i=0;
        $pgNo=$i+1;
        $addToArray=array (
            $i => 
            array (
              'fileName' => "$file",
              'pageNr' => $pgNo,
            )
            );
        array_push($files_array, $addToArray);
    }

    $json_array=array (
        'md' => 
        array (
          'title' => "$title",
        ),
        'pageList' => 
        array (
          'pages' => 
          json_encode($files_array, JSON_PRETTY_PRINT),
        ),
    );
    
    $json_pretty = json_encode($json_array, JSON_PRETTY_PRINT);
    echo $json_pretty;
    }

json_generate();

?>

    You've got a json_encode in the middle of the array you're building for $json_array, which you json_encode again a moment later. That's probably incorrect (because it will give you {"pageList": {"pages": "[...]"}}, not {"pageList": {"pages": [...]}}).

      Write a Reply...