Convert php data to Json - Stack Overflow
PHP Array to Json Object - Stack Overflow
Returning JSON from a PHP Script - Stack Overflow
Reading json with PHP. json_decode() is not working
The last item in the second object is:
"ignored" : 0,
Get rid of the comma. https://jsonlint.com/
More on reddit.comHow do I convert a PHP array to JSON?
When would I need to convert PHP array to JSON?
What PHP array features cannot be converted to JSON?
You want to json_encode($json, JSON_FORCE_OBJECT).
The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.
You can also eliminate the use of array_push for some slightly cleaner code:
$json[] = ['ip' => $ip, 'port' => $port];
just use only
$response=array();
$response["0"]=array("ip" => "192.168.0.1",
"port" => "2016");
$json=json_encode($response,JSON_FORCE_OBJECT);
While you're usually fine without it, you can and should set the Content-Type header:
<?php
$data = /** whatever you're serializing **/;
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
If I'm not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes print_r the data payload to eyeball it (though in most cases, it shouldn't be necessary).
A complete piece of nice and clear PHP code returning JSON is:
$option = $_GET['option'];
if ( $option == 1 ) {
$data = [ 'a', 'b', 'c' ];
// will encode to JSON array: ["a","b","c"]
// accessed as example in JavaScript like: result[1] (returns "b")
} else {
$data = [ 'name' => 'God', 'age' => -1 ];
// will encode to JSON object: {"name":"God","age":-1}
// accessed as example in JavaScript like: result.name or result['name'] (returns "God")
}
header('Content-type: application/json');
echo json_encode( $data );