PHP json_encode JSON_PRETTY_PRINT: how to print a different format?

laukok picture laukok · Sep 27, 2013 · Viewed 14.9k times · Source

I know that PHP provide the JSON_PRETTY_PRINT to format a json data already. What if I want a different format?

$message = array(
    "Open all day" => "Sundays,Saturdays,12-12-2013, 14-10-2013",

    "Availabilty" => array(
        "12/12/2013" => array(
            30,
            60,
            30,
            0
        ),
        "13/12/2013" => array(
            30,
            0,
            30,
            60,
        ),
    ),

);

$json = json_encode($message,JSON_PRETTY_PRINT);

result,

{
    "Open all day": "Sundays,Saturdays,12-12-2013, 14-10-2013",
    "Availabilty": {
        "12\/12\/2013": [
            30,
            60,
            30,
            0
        ],
        "13\/12\/2013": [
            30,
            0,
            30,
            60
        ]
    }
}

But I prefer,

{"Open all day":"
Sundays, 
Saturdays,
Fridays,
12/12/2013, 
14/10/2013, 
04/12/2013
",

"Availability":"
"12/12/2013":[30,60,30,0],
"13/12/2013":[30,60,30,0]
"}

Is that possible? A regex perhaps? Also, I don't want those backslashes - can they be removed?

Answer

Amal Murali picture Amal Murali · Sep 27, 2013

It isn't possible to get that format using json_encode alone.

But to prevent the slashes from being escaped, you could use the JSON_UNESCAPED_SLASHES constant:

$json = json_encode($message,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

See the documentation here.

Demo!