I am using this php code which works flawless for one file but when I upload multiple files generated json contains error.
$response = array('file' => ''.$file.'', 'date' => ''.date("d:m:y").'', 'save' => ''.$saving.'%');
echo json_encode($response);
If I am using one file the json output is valid
{"file":"http:\/\/xyy.com\/3\/4\/23968281479202046440249.png","date":"15:11:16","save"
:"<br>Original Size:8.3 Kb, Compressed Size:2.9Kb, Saving:65%"}
but if I am using two or more files json output is invalid and contains error.
{"file":"http:\/\/xxxxxxx.com\/4\/352118314792022053319009.png","date":"15:11:16","save"
:"Saving:68%"}{"file":"http:\/\/way2enjoy.com\/pdf\/1\/2\/3\/4\/270182314792022054204908.png","date":"15:11:16"
,"save":"Saving:65%"}
Any help will be great to make it work for multiple files.
The string with two file objects looks like a couple of JSON objects printed one after another. You should join the arrays before encoding and printing them in order to produce a valid JSON object, e.g.:
$date = date("d:m:y");
$response = [
['file' => $file1, 'date' => $date, 'save' => $saving.'%'],
['file' => $file2, 'date' => $date, 'save' => $saving.'%'],
];
// Also, use the correct MIME type for JSON content
header('Content-Type: application/json');
echo json_encode($response);
Otherwise, make separate HTTP requests for each file.
Related
I have a Rest API that accepts a Json Payload, i format the Data and import this into the SQL Database. However when the payload is received the sender is waiting for a response.
They do not want a Typical HTTP 200 OK, they want a formatted Json Response with the Price etc for the submission.
Whenever i output the response to the body, it does not appear to be formatted as a Json and appears as a string, this is causing errors with the flow of the program.
i wanted to check the formatting is correct and the method.
ignoring all the handler and authorization i am typically picking up the payload via:
$payload = (file_get_contents('php://input'));
do what i need to do with the data
then respond as follow:
(of course this is wrapped in a statement of handlers but the successful segment of the code)
http_response_code(200);
$data = array(
"sub_total" => 1000,
"ExtraeChargeTotal" => 0,
"Vat" => 0,
"Total" => 1000
);
$response = json_encode($data);
echo $response ;
is this the correct way to respond? everything works how i think it should, an appears to work in postman.
however the response is a string and not in Json
To resume the comments, when json datas must been sent with PHP, it's important to force the Content-Type header by this way :
header('Content-Type: application/json; charset=utf-8');
After the header, send the datas with echo.
For exemple in this case :
http_response_code(200);
$data = array(
"sub_total" => 1000,
"ExtraeChargeTotal" => 0,
"Vat" => 0,
"Total" => 1000
);
if($response = json_encode($data)){
header('Content-Type: application/json; charset=utf-8');
echo $response ;
}
I'm trying to get PHP returned array from Ajax.
Here is my Ajax call:
And my PHP code is this:
Query is running perfectly.
I have tried to get values like alert(data[0].program_title) in ajax success. But it also returns Undefined.
How can I fix this issue?
In your PHP code:
//remove
return $data
//change with
echo json_encode($data);
Just before flushing the data back to the stream (returning), convert your data ($data variable in this case) to JSON string using json_encode and add the proper content-type application/json using header function.
However, the best practice is to provide some metadata to your data included in your transfer, like the size of data and count of elements in data and if paginated, which page the data refers to and what the maximum available pages and maximum element size of a page are.
Here's a sample body structure for a more robust data transfer:
$response = [
'page' => 0, // e.g.
'count' => count($data),
'data' => $data,
'max_page' => 3, // e.g.
'item_per_page' => 15, // e.g.
'status_code' => 200, // e.g.
];
header ( "Content-Type: application\/json", true , 200);
return json_encode(
$response
, JSON_INVALID_UTF8_SUBSTITUTE
| JSON_NUMERIC_CHECK
| JSON_PRESERVE_ZERO_FRACTION
| JSON_UNESCAPED_LINE_TERMINATORS
| JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
);
Try this:
$data = [];
if ($numRows>0) {
while($row=$result->fetch_assoc()) {
$data[] = $row;
}
}
Replace return with echo and add json_encode
echo json_encode($data);
I'm building a simil web-service in php. This web service can read all record from a table of database and return a list of it in json format.
This is the code of my getArticoli.php file:
<?php
require_once('lib/connection.php');
$query_Articolo = "SELECT CodArticolo,NomeArticolo,Quantita,CodiceBarre, PrezzoAttuale, PrezzoRivenditore,PrezzoIngrosso
FROM VistaArticoli ";
$result_Articoli = $connectiondb->query($query_Articolo);
$answer = array ();
while ($row_Articoli = $result_Articoli->fetch_assoc()) {
$answer[] = ["id" => $row_Articoli['CodArticolo'],
"nome" => '"' . $row_Articoli['NomeArticolo'] . '"',
"quantita" => $row_Articoli['Quantita'],
"codiceBarre" => $row_Articoli['CodiceBarre'],
"codartFornitore" => $row_Articoli['CodiceBarre'],
"PrezzoAttuale" => $row_Articoli['PrezzoAttuale'],
"prezzoRivenditore" => $row_Articoli['prezzoRivenditore'],
"prezzoIngrosso" => $row_Articoli['prezzoIngrosso']];
}
//echo "fine";
echo json_encode($answer);
?>
Now, if I try to open this page, with this url: http://localhost/easyOrdine/getArticoli.php
I don't get the json_response.
In the table of database, there are 1200 records. If I try to insert an echo message in while cycle, I see it.
I have noticed that the problem lays with this field:
"nome"=>'"'.$row_Articoli['NomeArticolo'].'"'
If I remove this field from the response, I can correctly see the json response.
In this field there are any character from a-z/0-9 and special character like "/ * ? - and other".
It is possible that these special character can cause any error of the json answer?
EDIT
I have limit at 5 my query and this is the response:
[{"id":"878","0":"ACCESSORIO PULIZIA PUNTE DISSALDANTE 3 MISURE","quantita":"1","codiceBarre":"DN-705100","codartFornitore":"DN-705100","PrezzoAttuale":"14.39","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"318","0":"ACCOPPIANTORE RJ11 TELEFONICO VALUELINE VLTP90920W","quantita":"20","codiceBarre":"5412810196043","codartFornitore":"5412810196043","PrezzoAttuale":"0.68","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"320","0":"ACCOPPIATORE AUDIO RCA VALUELINE VLAB24950B","quantita":"5","codiceBarre":"5412810214136","codartFornitore":"5412810214136","PrezzoAttuale":"1.29","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"310","0":"ACCOPPIATORE RJ45 VALUELINE VLCP89005W","quantita":"8","codiceBarre":"5412810228843","codartFornitore":"5412810228843","PrezzoAttuale":"0.38","prezzoRivenditore":null,"prezzoIngrosso":null},
{"id":"311","0":"ACCOPPIATORE USB2 VALUELINE VLCP60900B","quantita":"5","codiceBarre":"5412810179596","codartFornitore":"5412810179596","PrezzoAttuale":"1.80","prezzoRivenditore":null,"prezzoIngrosso":null}]
First, remove those extraneous quote characters. You don't need them and they could hurt you down the road:
while ($row_Articoli = $result_Articoli->fetch_assoc()) {
$answer[] = [
"id" => $row_Articoli['CodArticolo'],
"nome" => $row_Articoli['NomeArticolo'],
"quantita" => $row_Articoli['Quantita'],
"codiceBarre" => $row_Articoli['CodiceBarre'],
"codartFornitore" => $row_Articoli['CodiceBarre'],
"PrezzoAttuale" => $row_Articoli['PrezzoAttuale'],
"prezzoRivenditore" => $row_Articoli['prezzoRivenditore'],
"prezzoIngrosso" => $row_Articoli['prezzoIngrosso']
];
}
Then, run your query as is (without the LIMIT), and afterwards run echo json_last_error_msg()';, which could give you a hint to what's going on.
Also, being that your DB is in italian, maybe its encoding is not UTF-8. json_encode requires UTF-8 encoded data. So you may try to utf8_encode your article names before json_encoding the array:
"nome" => utf8_encode($row_Articoli['NomeArticolo']),
And see what you get.
Changing your DB charset to 'utf8mb4' could do the trick as well, and it is usually recommended.
i need to append some elements to json file
this is my code:
routes.php (stage1)
$array = ['id' => '1', 'number' => '123123', 'name' => 'ahmed'];
$json_array = json_encode($array);
Storage::append('test.json', json_encode(['user_name' => 'ahmedsk']));
test.json
{"user_name":"ahmedsk"}
{"id":"1","number":"24142","username":"ahmedsk"}
but when i make print_r() for $result it's not feedback
routes.php (stage2)
$result = Storage::get('test.json');
print_r($result);
With knowing i don't need to use the method of get all data from JSON file and edited it and resave it in file.
Thanks
The question is some how vague.
if you need to print the json file as an array this is what you need :
routes.php (stage2)
$result = Storage::get('test.json');
print_r(json_decode("[" . preg_replace("/\n+/",",",$result) . "]"));
test :
https://eval.in/499591
Not an experienced developer and using CodeIgniter for the first time. I'm trying to grab a signed URL for a given MP3 filename stored in S3. This is currently working with the exception of files that contain brackets.
Relevant controller code:
function index ($streamfile) {
// Load S3 client
$this->load->spark('amazon-sdk');
$s3 = $this->awslib->get_s3();
// Define request parameters
$s3bucket = $userdata['s3bucket']; // defined elsewhere
$streamfiletest = ($string)'Crazy_(Remix).mp3';
// Request signed URL
$url = $s3->get_object_url($s3bucket, ***EITHER $streamfiletest or $streamfile***, '5 minutes');
// Fetch status code
$http = new CFRequest($url);
$http->add_header('Content-Type', '');
$http->send_request(true);
$code = $http->get_response_code();
$headers = $http->get_response_header();
// Load the view
$data['filename'] = $url;
$data['debug'] = array(
'file1' => $streamfile,
'file2' => $streamfiletest,
'signed_url' => $url,
'code' => $code,
'headers' => $headers
);
$this->load->view('play', $data);
Relevant view code:
<?php if (isset($debug)) {
echo "DEBUGS:";
echo '<pre>' . print_r($debug, TRUE) . '</pre>';
} ?>
As you can see I either pass $streamfile or $streamfiletest. In the debug I can confirm that both variables are the same string.
When passing $streamfile to the URL request, the URL in the response is incorrect:
DEBUGS:
[file1] => Crazy_(Remix).mp3
[file2] => Crazy_(Remix).mp3
[signed_url] => http://s3-...(removed)/Crazy_%26%2340%3BRemix%26%2341%3B.mp3?AWSAccessKey...
[code] => 404
You can see that the brackets have been strangely encoded %26%2340%3B and therefore I can't find the file in S3.
When passing $streamfiletest however, the response is fine:
DEBUGS:
[file1] => Crazy_(Remix).mp3
[file2] => Crazy_(Remix).mp3
[signed_url] => http://s3-...(removed)/Crazy_%28Remix%29.mp3?AWSAccessKey...
[code] => 200
The brackets are encoded correctly in the signed URL an I get a HTTP 200 from S3.
Any ideas what could be causing this?
In the debug I can confirm that both variables are the same string
Actually, not quite.
If you look closely, it becomes apparent what the url escaped values must mean:
%26%2340%3B %26%2341%3B
& # 40 ; & # 41 ;
Those are numeric html character codes that the browser will display as ( and ) but it does not in fact mean that the two strings have identical content. They only appear to.
The solution, of course, depends on how they are getting transformed that way, and either not doing that, or decoding the numeric character codes.
Try doing the following to decode the url encoded brackets
$data['filename'] = urldecode($url);
This should return the string to its expected format ie with brackets