-1

here is my problem:

I want output a formatted array on my webserver, like this:

{
    "status": true,
    "motd": "    [  Mineplex Games  ]    \n        \u2744 New Game \u2744 Gladiators \u2744",
    "version": "1.8",
    "players": {
        "online": 24410,
        "max": 24411
    },
    "ping": "0.039",
    "cache": 1450047242
}

In the source of that page there is not <pre> tag, but I don't know how to reproduce that result without that tag.

How can I do that? Here is my code

  echo '<pre>';
  print_r($array);
  echo '</pre>';

EDIT: echo json_encode($array); will output a non-formatted text, just a line.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
user324964
  • 3
  • 1
  • 5
  • 1
    That's JSON, not a PHP array, and it must have some kind of pre-formatting tag or styles added to it for it to render that way unless you're just looking at the source code – scrowler Dec 13 '15 at 23:00
  • echo json_encode($array); will output a non-formatted text, just a line. – user324964 Dec 13 '15 at 23:06
  • If you're working on a JSON string, then you'll need to convert it to a PHP array first with json_decode. – Ultimater Dec 13 '15 at 23:07
  • Are you saying print_r works fine with `pre` but doesn't work without `pre`? That is because your page is rendering in HTML which treats redundant whitespace as a single space thus ignoring linebreaks. If you clicked "view source" of your HTML page, you'll see print_r doesn't output it on a single line, it actually uses multiple lines. You can similarly use `header("Content-Type:text/plain");` at the top of your page to make the spacing meaningful. If you need the newlines `\n` to be converted to `
    ` there's http://php.net/manual/en/function.nl2br.php
    – Ultimater Dec 13 '15 at 23:16

3 Answers3

5

You probably want to set a mime-type other than text/html. try text/plain (will show like when used html with <pre>) for example or application/json (the official type for json)

In PHP, use the following lines:

header('Content-Type: application/json');
echo json_encode($array, JSON_PRETTY_PRINT);
Daniel Alder
  • 5,031
  • 2
  • 45
  • 55
1

That is JSON, try echo json_encode($array);

edit: For a formatted result, json_encode takes a second parameter.

Try this echo json_encode($array, JSON_PRETTY_PRINT);

smddzcy
  • 443
  • 4
  • 19
0

If you're just looking to add line breaks between elements, you can can try:

echo implode("<br>", $array);
cantelope
  • 1,147
  • 7
  • 9
  • i don't want html tags in the page! it's like the page should download array.json file – user324964 Dec 13 '15 at 23:13
  • You could output the array to a file named something.txt and redirect the user to that file. Text files render verbatim in most browsers, including line breaks, without html. – cantelope Dec 13 '15 at 23:22