Your PHP starts like this:

<html>
<body>

Whatever else it outputs after that, it isn't going to be valid JSON.

I did some debugging in chrome and under the network tab verified the response preview

Look at the raw preview. You seem to be looking at the rendered HTML preview.

Answer from Quentin on Stack Overflow
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.json-encode.php
PHP: json_encode - Manual
It will create a JSON-encoded string without throwing an error, but this string will cause an error when parsed. For example, the string "Example\" will cause the following error in JavaScript when parsing: JSON.parse: expected ',' or '}' after property value in object This appears to be an oversight in the JSON specification and the only work-around appears to be removing trailing slashes from all strings before encoding.
๐ŸŒ
Medium
medium.com โ€บ @onwuka_gideon โ€บ how-i-fixed-php-json-encode-returning-empty-result-e4ef97638ea1
How I fixed PHP json_encode() returning empty result | by Onwuka Gideon | Medium
May 31, 2019 - How I fixed PHP json_encode() returning empty result If you are building a RESTful API in PHP, then you are most likely using the json_encode function. json_encode is a PHP function that converts an โ€ฆ
Discussions

php - Why would json_encode return an empty string - Stack Overflow
I have a simple php structure with 3 nested arrays. I do not use particular objects and I build myself the arrays with 2 nested loops. Here is a sample of the var_dump of the array I want to conver... More on stackoverflow.com
๐ŸŒ stackoverflow.com
json_encode shows empty objects
There was an error while loading. Please reload this page ยท Hi, i need to pass a Query result as JSON, but my return is that: More on github.com
๐ŸŒ github.com
5
May 30, 2017
javascript - JSON encoding with Services_JSON and json_encode in PHP returning empty object with jQuery ajax call - Stack Overflow
Why would I not receive a response back to my jQuery code with a JSON-encoded string? ... How do you know it's empty? I don't see you logging it to the console. console.log('response: ' + resp); will convert the object to a string first, and the default string representation of an object is ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 5, 2013
php - Why json_encode returns empty brackets? - Stack Overflow
var_dump of $array returns this : array (size=3) 0 => object(frontend\models\Notifications)[101] private '_attributes' (yii\db\BaseActiveRecord) => array (size=5) ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 26, 2017
๐ŸŒ
GitHub
github.com โ€บ parse-community โ€บ parse-php-sdk โ€บ issues โ€บ 319
json_encode shows empty objects ยท Issue #319 ยท parse-community/parse-php-sdk
May 30, 2017 - parse-community / parse-php-sdk Public ยท There was an error while loading. Please reload this page. Notifications ยท You must be signed in to change notification settings ยท Fork 341 ยท Star 808 ยท New issueCopy link ยท New issueCopy link ยท Closed ยท Closed ยท json_encode shows empty objects#319 ยท Copy link ยท mauriciord ยท opened ยท on May 30, 2017 ยท Issue body actions ยท Hi, i need to pass a Query result as JSON, but my return is that: [{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}] My code: $lotQuery = new ParseQuery("Loteamento"); $lotQuery->notEqu
Author: parse-community
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 15830446 โ€บ json-encoding-with-services-json-and-json-encode-in-php-returning-empty-object-w
javascript - JSON encoding with Services_JSON and json_encode in PHP returning empty object with jQuery ajax call - Stack Overflow
April 5, 2013 - I have also tried the PHP built-in function json_encode: echo json_encode(array('ajax' => 1, 'feature' => 'rfc1872')); exit; Neither of these work and although I don't fall into the error callback in the jQuery ajax call above I get a response value of response: [object Object] with an empty object in Firebug.
๐ŸŒ
Shounak Gupte
shounakgupte.com โ€บ json_encode-returns-an-empty-string
How to fix PHP json_encode which returns an empty string
April 13, 2015 - If you are trying to grab some information through a web service in JSON format and if PHP function json_encode returns you an empty string, you need to convert the JSON object to UTF8.
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 25949259 โ€บ json-encode-an-empty-array-used-in-javascript-gives-an-empty-array-but-if-json-e
php - json_encode an empty array used in javascript gives an empty array but if json_enode is done on array with some values, it gives object? - Stack Overflow
September 20, 2014 - Yes. But is there any way so I don't have to do further checking to find out whether it is an array or object. 2014-09-20T13:32:30.813Z+00:00 ... Save this answer. ... Show activity on this post. Because the keys in your array don't start at 0, PHP's json_encode outputs the result as an object.
Top answer
1 of 4
160

Recommended method

json_decode ("{}") will return a stdClass per default, using the below should therefor be considered safe/portable and correct.

json_encode (new stdClass);


Your solution could work..

The documentation specifies that (object) null will result in an empty object, some might therefor say that your code is valid and that it's the method to use.

PHP: Objects - Manual

If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty.

.. but, try to keep it safe!

Though you never know when/if the above will change, so if you'd like to be 100% certain that you will always will end up with a {} in your encoded data you could use a hack such as:

$empty = json_decode ("{}");
$result = json_encode($empty); // "{}"

Even though it's tedious and ugly I do assume/hope that json_encode/json_decode is compatible with one another and always will evaluate the following to true:

$a = <something>;

$a === json_decode (json_encode ($a)); 
2 of 4
112

If you use objects as dynamic dictionaries (and I guess you do), then I think you want to use an ArrayObject.

It maps into JSON dictionary even when it's empty. It is great if you need to distinguish between lists (arrays) and dictionaries (associative arrays):

$complex = array('list' => array(), 'dict' => new ArrayObject());
print json_encode($complex); // -> {"list":[],"dict":{}}

You can also manipulate it seamlessly (as you would do with an associative array), and it will keep rendering properly into a dictionary:

$complex['dict']['a'] = 123;
print json_encode($complex); // -> {"list":[],"dict":{"a":123}}

unset($complex['dict']['a']);
print json_encode($complex); // -> {"list":[],"dict":{}}

If you need this to be 100% compatible both ways, you can also wrap json_decode so that it returns ArrayObjects instead of stdClass objects (you'll need to walk the result tree and recursively replace all the objects, which is a fairly easy task).

Gotchas. Only one I've found so far: is_array(new ArrayObject()) evaluates to false. You need to find and replace is_array occurrences with is_iterable.

๐ŸŒ
Reddit
reddit.com โ€บ r/laravel โ€บ any ideas about why json_encode would return empty for a request on local dev, but not empty on server?
r/laravel on Reddit: Any ideas about why json_encode would return empty for a request on local dev, but not empty on server?
October 16, 2021 -

I have a function written like this in my Laravel controller:

    /**
     * @param Request $request
     *
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Throwable
     */
    public function saveFreshBatch(Request $request)
    {
        Log::info("Received a new fresh batch... " . json_encode($request));
    ...

On my local, I get the following in my logs: "Received a new fresh batch... ", so a string followed by an empty array, with no text afterward, which means the result of json_encode($request) was blank. However, the object is full of data. I ran the debugger and it returned this:

> json_encode($request)
< {"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}

However, json_encode($request->all()) returns the correct string as if doing the whole thing, even on local.

On the production (Dev) server, I get a full JSON output, so a gigantic PHP array. In both cases I notice $request->all() gives full code.

Any ideas why the same code would result in different output, for the same object? The only thing I can think of is the headers are different, or the subclassed request is different.

Why does json_encode($request) return different outputs for the same HTTP request?

Top answer
1 of 1
1

You really should include the actual JSON in your question; without it we are working blind, but I can guess what the problem is. You are not constructing your JSON properly when there are multiple records. When you have a single recipient, your JSON might look like this:

{"readyState":4,"responseText":"","status":200,"statusText":"OK"}

That is fine, and perfectly valid JSON โ€“ and there is no issue having an empty string as a value. The problem arises when you have more than one record, when it will append them immediately after the first:

{"readyState":4,"responseText":"","status":200,"statusText":"OK"}{"readyState":4,"responseText":"","status":200,"statusText":"OK"}

This is not valid JSON.

I suggest you accumulate your JSON responses inside the loop and then output them afterwards, in the correct format. Something like:

$jsonData = [];
foreach ($emails_room_f as $email_room_f){
    //set your content in $data as you are now, then:
    $jsonData[] = $data;
}
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($jsonData);

This way you will end up with data like this:

[
    {"readyState":4,"responseText":"","status":200,"statusText":"OK"},
    {"readyState":4,"responseText":"","status":200,"statusText":"OK"}
]

Which is valid JSON. It will also work if there is no data as it will return an empty array, which is also valid JSON.

Separately from this, I am extremely suspicious of you having a utf8ize function โ€“ that is a sign you're doing other UTF-8 stuff wrong, but that's a subject for another question.

๐ŸŒ
Blogger
anvnguyen.blogspot.com โ€บ 2015 โ€บ 07 โ€บ php-jsonencode-return-empty-array.html
PHP json_encode return empty array [] instead of empty object {}
July 27, 2015 - If so, follow this simple solution: Developer just uses normal array() function and then use flag JSON_FORCE_OBJECT when encode the array: ... JSON_FORCE_OBJECT (integer) Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 13871973 โ€บ empty-array-in-php-json-js-empty-array-in-javascript-how-to-get-empty-o
Empty array in PHP -> JSON -> JS = empty array in Javascript. How to get empty Object instead? - Stack Overflow
December 14, 2012 - Hmm, interesting, but there are other arrays in $this->_response that should remain empty arrays. ... It's a known limitation of PHP - since it doesn't support JavaScript types natively (eg. objects), decoding and then encoding again may lead to data loss. I use a workaround like this to keep JSON in tact: /** * @param $input * @return array */ public static function safeDecode($input) { // Fix for PHP's issue with empty objects $input = preg_replace('/{\s*}/', "{\"EMPTY_OBJECT\":true}", $input); return json_decode($input, true); } /** * @param array|object $input * @return string */ public static function safeEncode($input) { return preg_replace('/{"EMPTY_OBJECT"\s*:\s*true}/', '{}', json_encode($input)); }
๐ŸŒ
w3tutorials
w3tutorials.net โ€บ blog โ€บ why-would-json-encode-return-an-empty-string
Why Does json_encode Return an Empty String in PHP? Troubleshooting Nested Arrays โ€” w3tutorials.net
json_encode() returning an "empty string" is almost always a sign it failed (returned false), often due to issues in nested arrays. By checking for errors with json_last_error(), validating UTF-8 encoding, inspecting data types, and handling ...