Trying to send arraylist data to server using php as bridge from Android (using Volley), and successfully getting data into database table (and also getting response as submit, I mentioned in php) in Android
So everything looks perfect, if we talk about db connection, storage and response, but one unusal issue always getting 2 in table field, instead the original value
::::imageDataInString::::: {"b":"2020-01-01_00:01:11.jpg"}
::::imageDataInString::::: {"b":"2020-01-01_00:01:21.jpg"}
::::imageDataInString::::: {"b":"2020-01-01_00:01:31.jpg"}
::::Response::::: <br />
<b>Warning</b>: Illegal string offset 'image_name' in <b>C:\xampp\htdocs\test\send_data.php</b> on line <b>15</b><br />
<br />
submit
Here is the foreach, I'm using in php to upload all the data available in a list
$content = $_POST['my_images'];
$json = json_decode($content, true);
foreach ($json as $key => $value) {
$image_name = $value["image_name"];
}
android code
ImageData imageData = new ImageData();
imageData.setImageName(array[0]);
String imageDataInString = new Gson().toJson(imageData);
Log.d("::::imageDataInString::::", imageDataInString);
....
params.put("my_images", imageDataInString);
in my csv, available in raw folder of res in Android, I have these data:
2020-01-01_00:01:11.jpg
2020-01-01_00:01:21.jpg
2020-01-01_00:01:31.jpg
There are a few points to note:
GSON converts the variable names of the class (ImageData) as keys and appends the values, to form the JSON. Hence, you need to use the same variable names, as you have used in the ImageData class to fetch the data, in your PHP Code.
ImageData imageData = new ImageData();
imageData.setImageName(array[0]);
String imageDataInString = new Gson().toJson(imageData);
Hence, the array key should be array["ImageName"]
In your PHP code, the second line, where you are JSON decoding the $content variable, the variable $json is already converted in an Array. You don't need to iterate and fetch corresponding keys.
Hence, you should do something like this:
$content = $_POST['my_images'];
$json = json_decode($content, true);
$image_name = $json["ImageName"];
With this, the variable $image_name will hold the value which you are looking for.
Related
Output when success
string(66)
"{"status":true,"message":"success","data":{"amountDue":"-504.20"}}"
Output when error
string(119) "{"status":false,"message":"An error occured while getting
full subscriber profile: Subscription not found MPP servers"}"
How should I write in php to get the amount due from the output? I am new to REST api. Can someone show me ? Thank you
That is a JSON-encoded response. Use json_decode() to convert the string back into an array, and then access the array element:
$output = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$results = json_decode($output,true);
if($results["status"])
{
echo "Success! Data: " . print_r($results,true);
}
I assume that you can at least send proper request to the endpoint and you are able to capture the response.
You receive a json string which must be parses so if:
$response = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$responseArray = json_decode($response, true);
Then you will get a responseArray as associated array (the second parameter) so you can get amount due like that
$amountDue = $responseArray['data']['amountDue'];
You could also parse json data into an StdClass which turn all fields in json into an object's property. To do that abandon the second parameter in json_decode function
$resultObj = json_decode($response);
$amountDue = $resultObj->data['amountDue'];
All depends on your requests.
To read more about json_decode try documentation
Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:
[[DATE] America/New_York] PHP Notice: Undefined index: title in [...php] on line [...]
[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]
What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.
Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).
Would really appreciate any help with this, thank you!
Edit
This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.
The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
In full, with some abbreviation of the array building at the end for simplicity:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.
another (probably) easy question for you.
As I wrote many times, I'm not a programmer but thanks to you I was able to build an interesting site for my uses.
So again thx.
This is my new problem:
I have a site that recover json data from a file and store it locally once a day (this is the code - I post it so it can be useful to anyone):
// START
findList();
function findList() {
$serverName = strtolower($_POST["Server"]); // GET SERVER FROM FORM POST
$localCoutryList = ("json/$serverName/countries.json"); // LOCAL LOCATIONS OF FILE
$urlCountryList = strtolower("url.from.where.I.get.Json.file.$serverName/countries.json"); // ONLINE LOCATION OF FILE
if (file_exists($localCoutryList)) { // FILE EXIST
$fileLastMod = date("Y/m/d",filemtime($localCoutryList)); // IF FILE LAST MOD = FILE DATE TIME
$now = date('Y/m/d', time()); // NOW
if ($now != $fileLastMod) { // IF NOW != FILE LAST MOD (date)
createList($serverName,$localCoutryList,$urlCountryList); // GO AND CREATE FILE
} else { // IF NOW = FILE LAST MOD (date)
jsonList($serverName,$localCoutryList,$urlCountryList); // CALL JSON DATA FROM FILE
}} else { // FILE DOESN'T EXIST
createList($serverName,$localCoutryList,$urlCountryList); // CALL CREATE FILE
}};
function createList($serverName,$localCoutryList,$urlCountryList) {
file_put_contents($localCountryList, file_get_contents($urlCountryList)); // CREATE FILE
jsonList($serverName); // CALL JSON DATA FROM FILE
};
function jsonList($serverName,$localCoutryList,$urlCountryList) { // JSON DATA FROM FILE
$jsonLoopCountry = file_get_contents($localCoutryList); // GET CONTENT OF THE LOCAL FILE
$outLoopCountry = json_decode($jsonLoopCountry, true); // DECODE JSON FILE
$countryList = $outLoopCountry['country']; // ACCESS TO JSON OBJECT
foreach ($countryList as $dataCountry) { // FOR EACH "COUNTRY" IN JSON DECODED OBJECT
// SET VARS FOR ALL THE COUNTRIES
$iscountryID = ($dataCountry['id']); // TEST
$countryCurrency = ($dataCountry['curr']); // TEST
$countryName = ($dataCountry['name']);} // TEST
echo "<br>total country list: ".count($countryList); // THIS RETURN TOTAL ELEMENTS IN THE ARRAY
[...]
The kind of Json data I'm working with is structured as it follows:
{"country":[{"id":130,"curr":"AFN","name":"Afghanistan"},{"id":55,"curr":"ALL","name":"Albania"},{"id":64,"curr":"DZD","name":"Algeria"},{"id":65,"curr":"AOA","name":"Angola"},{"id":24,"curr":"ARS","name":"Argentina"}...
So I can say that
$outLoopCountry = json_decode($jsonLoopCountry, true); // DECODE JSON FILE
creates the JSON ARRAY right? (Because JSON array starts with {"something":[{"..."...)
if it was [{"a":"answer","b":"answer",...} ... it would have a been a JSON Object right?
So to access to the array I uses
$countryList = $outLoopCountry['country']; // ACCESS TO JSON OBJECT
right?
So I understood that arrays are a fast useful ways to store relational data and access to it right?
So the question is how to make a precise search inside the array, so to make it works like a Query MySQLi, like "SEARCH INSIDE ARRAY WHERE id == 7" and have as a result "== ITALY" (ex.).
The way exist for sure, but with whole exmples I found on the net, I was able to fix one to make it works.
Thx again.
Alberto
I've some JSON data in a javascript file
Data is build using javascript object literal notation;
var CMS = window.CMS = window.CMS || {};
CMS.Data = window.CMS.Data = window.CMS.Data || {};
CMS.Data['LANGUAGES'] = [
{id:"chi", value:"Chinese"},
{id:"spa", value:"Spanish"},
{id:'eng', value:"English"},
{id:"hin", value:"Hindi"},
];
CMS.Data['AGE_RANGE'] = [{id:'18', value:"18"}, {id:'25', value:"25"}, {id:'30', value:"30"}, {id:'35', value:"35"}, {id:'40', value:"40"}, {id:'50', value:"50"}, {id:'60', value:"60"}, {id:'70', value:"70"}, {id:'80', value:"80"}, {id:'90', value:"90"}, {id:'100', value:"100"}];
CMS.Data['HEIGHT_RANGE'] = [{id:'140-150', value:"140-150"}, {id:'150-160', value:"150-160"}, {id:'160-170', value:"160-170"}, {id:'180-190', value:"180-190"}];
Complete data is available at https://gist.github.com/mithunqb/675613fe985fe2afbbcf
I need to make it available in PHP array.
I cannot simply load the content and apply json_decode
$json_string = file_get_contents('data.json');
$json_array = json_decode($json_string, true);
As the content inside the json file is not actually a valid JSON string, the above operation will result NULL;
How can I do this?
If the JSON string is not valid then there is no way to convert it to PHP array. Not a chance at any circumstances. It's obvious.
You must provide a valid JSON string.
Sending a image to mysql using android, json and php
I was able to get my bitmap converted to a properly formatted string using
converting-images-to-json-objects
Here is the code in android
JSONObject values = new JSONObject();
values.put(KEY_CONTRACTUUID, con.UUID);
...
if (con._sig != null) {
String encodedImage = getStringFromBitmap(con._sig);
values.put(KEY_CONTRACTSIGIMAGE, encodedImage);
private static String getStringFromBitmap(Bitmap bitmapPicture) {
/*
* This functions converts Bitmap picture to a string which can be
* JSONified.
*/
final int COMPRESSION_QUALITY = 100;
String encodedImage;
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY,
byteArrayBitmapStream);
byte[] b = byteArrayBitmapStream.toByteArray();
encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
return encodedImage;
}
now that it is in base64 and a string I need to retrieve it properly to place in my BLOB in mysql
I am not using namevalue pairs or any of that nonsense - simply send it as json and get the json string like so:
$json = json_decode($HTTP_RAW_POST_DATA,true);
echo var_dump(HTTP_RAW_POST_DATA);
...
$varsigimage = $json['sigimage'];
$formatedJSONimage = "{'sigimage': '$varsigimage'}";
var_dump($formatedJSONimage);
$sigImagedecoded = json_decode($formatedJSONimage);
var_dump($sigImagedecoded);
i need to call json_decode on the image to get it out of 64bit to place in the blob correct?
However to do this I need to use the function json_decode, but json_decode assumes I will give it a JSONObject, and since I have many more objects in my $json object, i need to recreate a single JSON object with just the image inside of it, and pass that to the json_decode
but it retuns json_error of type SYNTAX
What am I doing wrong, What is the correct approach of converting the base64 string to a blob?
and yes, I am going to have the same question on getting it out of the blob back to a base64 string
json_decode parses a JSON string and returns an associative array, mimicking the key/value pairs in the JSON string.
It seems like you are missing another step: you need to decode the base64-encoded image string back to a bitmap. e.g. in your code:
$json = json_decode($HTTP_RAW_POST_DATA,true);
echo var_dump(HTTP_RAW_POST_DATA);
...
$varsigimage = $json['sigimage'];
$image_bitmap = base64_decode($varsigimage); // decode the string back to binary
You should now be able to save $image_bitmap as a BLOB in your database.