Skip to content
Advertisement

Wrapping json results in tag

I am trying to make my own API for my discord bot and i noticed the response looks like this: Showing JSON code in font Times New Roman font probably times new roman because it is not wrapped in a <pre> tag.

But when I DO wrap it in a <pre> tag to make it look like this: Showing JSON Code in font Monospace(font monospace) the contents have the tags in it…

For example these are the contents that are grabbed:

<pre>{"success":true,"type":"sha256","string":"Hello friend","hash":"ad7c4d7f20d11015260cd4609df255c99ebef944f59110167f2ff62a2c750072"}</pre>

The code:

<?php
    $json_array = json_encode(range(0,10));
    echo "<pre>{$json_array}</pre>";

I also tried this with no avail:

<?php
    header('Content-Type: application/json');
    $json_array = json_encode(range(0,10));
    echo $json_array;

How would I go about getting the json wrapped in the <pre> tag without it affecting how it grabs the content? I feel like I have looked everywhere but can’t find a thing. I know it can be done because an API I use gets wrapped in the <pre> tag and doesn’t have a problem retrieving the json.

Advertisement

Answer

Include this header('Content-Type: application/json'); and make sure you have NO empty spaces above your <?php tag!

That was the problem here, a simple empty space/line above the <?php tag.

So my second code block should’ve worked, had I not left an empty line above the <?php tag at the top of the PHP file. e.g:

Before (output.php):

<?php
    header('Content-Type: application/json');
    $json_array = json_encode(range(0,10));
    echo $json_array;
?>

After (output.php):

<?php
    header('Content-Type: application/json');
    $json_array = json_encode(range(0,10));
    echo $json_array;
?>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement