I am trying to sent response in that form
{"files":[{"webViewLink":""},{"webViewLink":""}]}
But I’m getting response like that
{"files":[{"webViewLink":"""}]}{"files":[{"webViewLink":"""}]}
Here is my PHP code:
<?php $idtemp = extractfiles($fol_id, $email); foreach ($idtemp['items'] as $val) { $id = $val['id']; $val = array( "webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"' ); $enc = json_encode($val); $val = '{"files":['.$enc.']}'; echo($val);
Please help me to fix code i need response in that way
{"files":[{"webViewLink":""},{"webViewLink":""}]}
Advertisement
Answer
You should no do $val = '{"files":['.$enc.']}';
Use json_encode
to make json, don’t do it manual
- Create an object with desired keys outside the loop
- Push anything to the desired array
- Convert to json
<?php $idtemp = extractfiles($fol_id, $email); $json = (object) [ "files" => [] ]; foreach ($idtemp['items'] as $val) { $json->files[] = (object) [ "webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"' ]; } $json = json_encode($json); echo($json);
If I use some dummy values to create an example, the output is:
{ "files": [ { "webViewLink": "https://drive.google.com/file/d/1/view?usp=drivesdk"" }, { "webViewLink": "https://drive.google.com/file/d/2/view?usp=drivesdk"" }, { "webViewLink": "https://drive.google.com/file/d/3/view?usp=drivesdk"" } ] }
As you can test in this online demo