Print JSON formatted using PHP

Asked

Viewed 672 times

0

I have the following code:

<?php

    $arquivo = scandir("Arquivo");

    $data = array();

    foreach ($arquivo as $img) {
        if (!in_array($img, array(".",".."))) {

            $filename = "Arquivo" . DIRECTORY_SEPARATOR . $img;

            $info = pathinfo($filename);

            $info["size"] = filesize($filename);

            array_push($data, $info);

        }   
}


echo json_encode($data);

?>

And I can’t print JSON with Line break, the information goes side by side.

Screenshot of how the code is coming out

In the attached image it shows how the information is coming out and in the image it also has a notepad showing how accurate the information is printed.

Any suggestions?

1 answer

1

You can use the JSON_PRETTY_PRINT from PHP to this or send a suitable Content-Type, so that in the browser it interprets JSON and can "format" it. But remember that both Jsons (with or without "line break") are identical and are treated the same.

1. Content-Type:

header('Content-Type: application/json'); 

echo json_encode($data, JSON_PRETTY_PRINT); // Provável que em 99% dos navegadores usar o json_encode($data) ficará formatado também, devido ao header acima.

2. HTML:

Note: this will not be a valid JSON!

echo "<pre>" . json_encode($data, JSON_PRETTY_PRINT) . "</pre>"

Choose one of the options that best fit your use case.

Browser other questions tagged

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