Skip to content
Advertisement

How to add a line break in brackets and braces JSON PHP file?

I have the following code that generates data in json php:

<?php
    $stmt = $con->prepare("SELECT
                                id_news,
                                url,
                                cover_page,
                                alt_img,
                                mini_title,
                                mini_description,
                                date_post,
                                confg_img,
                                main_cover
                            FROM news ORDER BY id_news DESC LIMIT 5");
        $stmt->execute();
        $member = array();
        $stmt->bind_result(
            $member['id_news_sport'],
            $member['url'],
            $member['cover_page'],
            $member['alt_img'],
            $member['mini_title'],
            $member['mini_description'],
            $member['date_post'],
            $member['confg_img'],
            $member['main_cover']
        );

        header('Content-type: application/json; charset=utf-8');
        echo '[';
        $count = 0;
        while ($stmt->fetch()) {
            if( $count ) {
                echo ',';
            }

            echo json_encode($member, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_FORCE_OBJECT);

            ++$count;
        }

        echo ']';
 ?>

Obtaining the following result:

[{
    "id_news": 712,
    "url": "es/deportes/futbol/ecuador/ligapro/serie-a/712/marcos-caicedo-recuerda-su-paso-en-los-equipos-del-astillero",
    "cover_page": "https://i.imgur.com/kg7RBqK.jpg",
    "alt_img": "Marcos Caicedo",
    "mini_title": "Marcos Caicedo recuerda su paso en los equipos del astillero",
    "mini_description": "El jugador de Liga de Quito no olvida su paso por Emelec y Barcelona",
    "date_post": "2020-12-18 03:21:57",
    "confg_img": null,
    "main_cover": "relevant_news"
},{
    "id_news": 708,
    "url": "es/deportes/futbol/internacional/fichajes/708/el-fichaje-que-pretendia-ldu-para-la-defensa-podria-caerse",
    "cover_page": "https://i.imgur.com/MmETkch.png",
    "alt_img": "Jugadores de LDU celebrando un gol",
    "mini_title": "EL fichaje que pretendu00eda LDU para la defensa podru00eda caerse",
    "mini_description": "LDU tiene un competidor por el fichaje del central",
    "date_post": "2020-12-16 20:26:51",
    "confg_img": null,
    "main_cover": "relevant_news"
}]

But I need to be able to get a line break between the bracket and another line break for each brace, like this:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 10,
    "id": 99,
    "title": "temporibus sit alias delectus eligendi possimus magni",
    "body": "quo deleniti praesentium dicta non quodnaut est molestiasnmolestias et officia quis nihilnitaque dolorem quia"
  },
  {
    "userId": 10,
    "id": 100,
    "title": "at nam consequatur ea labore ea harum",
    "body": "cupiditate quo est a modi nesciunt solutanipsa voluptas error itaque dicta innautem qui minus magnam et distinctio eumnaccusamus ratione error aut"
  }
]

As this json data output is shown, what changes should I use in my PHP JSON code to obtain the same result.

Advertisement

Answer

HTML

If you are likely to be displaying the resulting JSON to users in a web browser, you can simply use: echo "[<br>"; and echo "<br>]"; to insert html linebreaks.

API/REST Script

If the result is being handled by any other application other than a web browser, use:

  • echo "[ n"; and echo "n ]"; for programs on Linux/Unix Based Systems (Including MacOS 10+)
  • echo "[ r"; and echo "r ]"; for programs on MacOS Versions Lower than 9
  • echo "[ rn"; and echo "rn ]"; for programs on Windows Based Systems

The backslash is the universal “escape” character so if you are unsure about which platform you will be running the script on or want the output to be universal regardless of OS, use the windows format of ‘rn’ and each OS will work it’s own magic

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement