I have an array like this:
$json = '{ some already encoded json }';
$data = [
'success' => $this->isSuccess(),
'message' => $this->getMessage(),
'statusCode' => (string)$this->getStatusCode(),
'data' => $json
];
in another function I call
json_encode ($data)
The problem is that the json_encode encodes also the already encoded json in the 'data' parameters and escapes it.
How can avoid this ? Is there a straightforward way to do this without changing my whole application ?
I would like to return a json like this:
{ 'success' : true, 'message': 'my message', 'statusCode': 200, 'data': { some already encoded json }}
I'd recommend decoding the json when appending it to data key in the array and later encode everything to json. Like this:
$json = '{ some already encoded json }';
$data = [
'success' => $this->isSuccess(),
'message' => $this->getMessage(),
'statusCode' => (string)$this->getStatusCode(),
'data' => json_decode($json)
];
json_encode($data);
Related
I'm working on Lavravel 9 with guzzle to send some data in
the below code need to get some data from the database how can get data from the database?.
$response = Http::post('APIurl', [
"headers" => [
//header information
],
"body" => [
'title' => "**Get data from database**",
'body' => "**Get data from database**,
'userId' => 22
],
]);
Thank you
Assuming your API returns a json result, simply call the json() method on the Response object. If you want the raw response body, use body() instead.
For example, take github's api:
$response = Http::get('api.github.com'); // replace with your call
$body = $response->body(); // returns string
$json = $response->json(); // tries to return a json array.
To add data to your request, try passing a json string in the body.
$data = json_encode([
'title' => ...,
'body' => ...,
'user_id' => ...,
]);
$response = Http::post('your-api-here', [
'headers' => [
...
],
'body' => $data,
]);
This is the Request body that I need to send- (Curl POST request in PHP)
$data = {
"paramOne" : "f733787d-5649",
"paramTwo": {
"format": "123XD"
},
"paramThree": [
{"type":"cn", "value":"Test User Manish 1"},
{"type":"c", "value":"US"}
]
};
I'm trying to use it at this line of my Curl Request in PHP-
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
The nested params are messing up the format in which I'm trying to send.
I already tried using http_build_query but then paramThree is causing problems.
I'm looking for the changes that I need to make to the format of $data before I use http_build_query on it.
It's JSON. You can either post it as a string (enclosed in quotes) or make an array first, convert it to JSON and then post it. Like this:
$array = [
'paramOne' => 'f733787d-5649',
'paramTwo' => [
'format' => '123XD'
],
'paramThree' => [[
'type' => 'cn',
'value' => 'Test User Manish 1'
],
[
'type' => 'c',
'value' => 'US'
]]
];
$data = json_encode($array);
In both cases use
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
I am posting data to my script file to receive data. In my script file, File.php, I am not able to get the object patient in the dumped results. When i do var_dump($get_patient_info->patient);,
it throws an error saying Object {patient} not found.
Could i be mapping the data wrongly?
PS: Beginner in Laravel
SendingData Controller
$hospitalData = [];
$hospitalData[] = [
'patient' => 'Mohammed Shammar',
'number' => '34',
],
$url = "https://example.com/file.php";
$client = new Client();
$request = $client->post($url, [
'multipart' => [
[
'name' => 'patient_info',
'contents' => json_encode($hospitalData),
],
],
]);
$response = $request->getBody();
return $response;
File.php
$get_patient_info = $_POST['patient_info'];
var_dump($get_patient_info);
Results
string(189) "[{"patient":"Mohammed Shammar","number":"34"}]"
You can json_decode and fetch the data as follows,
$temp = json_decode($get_patient_info);
echo $get_patient_info[0]->patient;
json_decode — Decodes a JSON string
Hope this helps.
I need to write a new geoJSON feature to a data.json file using php. Right now I'm writing my data to the file like so:
<?php
// Read from json file
$jsondata = json_decode( file_get_contents('data.json') );
// Add the new data
$jsondata []= array(
'measure_location'=> $_POST["measure_location"],
'measure_type'=> $_POST["measure_type"],
'measurement'=> $_POST["measurement"],
'note_text'=> $_POST["note_text"]
);
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($jsondata, JSON_PRETTY_PRINT);
// saves the json string in "data.json" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data.json', $jsondata));
?>
And this is what the data then looks like in data.json:
{
"measure_location": "52.370611247493486, 4.91587221622467",
"measure_type": "negative",
"measurement": "violence",
"note_text": ""
}
Could I adjust my PHP code to make the data look like so:
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
"4.91587221622467",
"52.370611247493486"
]
},
"properties": {
"type": "negative",
"input": "violence",
"note": ""
}
}
Got the answer thanks to charlietfl. Changed the php code to:
<?php
// Read from json file
$jsondata = json_decode( file_get_contents('data.json') );
// Add the new data
$jsondata [] = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => $_POST["measure_location"],
),
'properties' => array(
'type' => $_POST["measure_type"],
'input' => $_POST["measurement"],
'note' => $_POST["note_text"],
)
);
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($jsondata, JSON_PRETTY_PRINT);
// saves the json string in "data.json" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data.json', $jsondata));
?>
I cannot the code that works for you. I have tried many times. It produced a wrong format JSON. The correct code should be,
$jsondata -> features [] = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => $_POST["measure_location"],
),
'properties' => array(
'type' => $_POST["measure_type"],
'input' => $_POST["measurement"],
'note' => $_POST["note_text"],
)
);
It says invalid json
{"userDetails": "RefId": 565521, {"key":[{"SNO":"565566","Type":"0","Desc":"0"},{"SNO":"12","Type":"1","Desc":"0"}]}, "success":true}
I want to add RefId while including it says invalid json please see and let me know whr m i wrong
You have not written it correctly:
{
"userDetails": [{
"RefId": 565521,
"key": [{"SNO":"565566","Type":"0","Desc":"0"},{"SNO":"12","Type":"1","Desc":"0"}],
"success" : true
}]
}
Your json should be like that :
{"userDetails": {"RefId": 565521, "key":[{"SNO":"565566","Type":"0","Desc":"0"},{"SNO":"12","Type":"1","Desc":"0"}]}, "success":true}
And you should generate it like that :
$resultJson = array(
'userDetails' => array(
'refId' => $reference_id,
'key' => $arr
),
'success' => true
);
echo json_encode($resultJson);