Receive array of numbers in php (JSON) - php

I would like to get an array from my JSON in php.
This way I get the JSON string from URL in my android application:
JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", paramstodb);
To receive [phone=123] in php I use this:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
That is working for one phonenumber, but now I need more than one phonenumber.
The data in Logcat (reported with "Log.d("to php: ", paramstodb.toString())" ) is displayed as:
to php:﹕ [phone=[0127361744, 0132782422, 0137173813, 0142534646, 0123617637435, 013391339494, 01383375633, 013878942423, 013891748422, 01389487285, 014434354234, 01848481371, 018831789414, 021238133441231, 021371689411, 02183718454, 123, 456]]
How can I get all numbers in an array in php?
This is not working so far:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
$phpArray = json_decode($phone, true);
I hope you can help me again ;-)

If the JSON input to the PHP script really is this JSON
{ "phone": [ "123", "456", "789"] }
then PHP's json_decode should handle it without problems.
You can try this code to see it's actually working and use it to detect where something goes wrong:
// original JSON to send from the client
$jsonString = '{ "phone": [ "123", "456", "789"] }';
// build a query string with the JSON to send
$queryString = "?" . http_build_query(array("phone" => $jsonString));
echo "Query string to send is: " . $queryString . PHP_EOL;
// PHP side: this is not a real HTTP GET request, but to pretend we have
// got some data in, we'll use the same query string, parse it, and store it
// in $params
$incoming = parse_url($queryString, PHP_URL_QUERY);
parse_str($incoming, $params);
// now print contents of "phone" parameter
echo "URL parameter phone contains " . $params["phone"] . PHP_EOL;
// JSON-decode the "phone" parameter
var_dump(json_decode($params["phone"], true));
This should print:
Query string to send is: ?phone=%7B+%22phone%22%3A+%5B+%22123%22%2C+%22456%22%2C+%22789%22%5D+%7D
URL parameter phone contains { "phone": [ "123", "456", "789"] }
array(1) {
'phone' =>
array(3) {
[0] =>
string(3) "123"
[1] =>
string(3) "456"
[2] =>
string(3) "789"
}
}
which shows the JSON decodes to a proper PHP array. An array of strings, to be precise, and not numbers as requested. Turning the strings into numbers in PHP will be easy to do, but maybe you could also make sure on the call site that you send numbers and not strings.
If your original code does not work, I guess the incoming data is either no properly encoded JSON or there is some magic escaping going on (magic quotes hell, should be turned off in today's PHP, but could be a reason for garbled script input).
To make sure your JSON data is not truncated and to also save you from potential URL-encoding issues, I also suggest sending the JSON via HTTP POST, not HTTP GET.

Related

php decode JSON get values

I'm trying to decode JSON format
What I am sending is:
{
"id": 123,
"name": "John",
“surname”: “Smith”,
“department”: 3
}
I am sending POST with data via Postman, in the picture.
So, this is the data I want to decode:
"data_serever_received": "{ \"id\": 123, \"name\": \"john\", “surname”: “Smith”, “department”: 3 }"
I tried
$this->input->data["id"]
but it is not working.
How can I get the id, name, surname and etc. values?
Your JSON is invalid “ and ” are not ".
(Zoom in with your browser if you can't see the difference).
You need to start with valid JSON before you can parse it.
You can use json_decode to make it an array.
$json_array = json_decode($json_object);//$json_object will need to contain your json string.
then you can access like this:
echo $json_array["data"][“surname”];
PHP Doc on json_decode: http://php.net/manual/en/function.json-decode.php

Trying to understand how to format this PHP POST to a Curl POST format

I am connecting with an API via curl and POSTing to it.
The API support simply says that I should form my request as so:
"If you send a POST request to the correct URL with a content-type of JSON and a body like what's below you should be off to a good start:
{
"contact": {
"email": "justin#myapi.com",
"last_name": "Johnston",
"company": "MyApi",
"first_name": "Justin"
}
}
However, I think this is for a regular PHP post maybe and not for CURL which is what I am using.
So, the curl code I have is:
//Set Curl options
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "first_name=" . $db->f('fname') . "&last_name=" . $db->f('lname') . "&email=" . $db->f('Email') . "&company=" . $db->f('studio_name') . "");
However, when I run the POST, the response I get back from the API says:
{"error":"Invalid parameters. Should be a hash in the form { 'contact' : { } }."}
So, I am assuming that is because my POSTFIELDS are not correct, and I understand I need to lead with "Contact", but I am not sure how to format it and haven't been able to find an example. Any idears?
Thanks very much for any help you could give! I really do appreciate it!!
Craig
To expand on the comment I posted...
I think the problem is you're sending a string as the parameter, where
it should be a JSON object. just use json_encode() to encode an
array of data and send that via POST instead of the string you're
forming
You need to create a JSON string (usually by encoding an array of data):
$data = array(
"contact" => array(
"first_name" => $db->f('fname'),
"last_name" => $db->f('lname'),
"email" => $db->f('Email'),
"company" => $db->f('studio_name')
)
);
$data = json_encode($data);
This will give you the JSON you need to post, so just change your line of code setting the parameters to this:
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
Edit: As requested in a comment, I'll attempt to explain a little more:
The POST request is sent to the server, and you can send any data you want with the request. In the example given in the question, this is valid JSON and they have specified that the body of the request should also be JSON (I'm assuming in the same format):
{
"contact": {
"email": "justin#myapi.com",
"last_name": "Johnston",
"company": "MyApi",
"first_name": "Justin"
}
}
In my solution above I've explained how to get a string containing valid JSON for an array of data; this string can be sent as the contents of the request.
The problem with what you were trying is that the whole data would have literally been sent like this:
first_name=Justin&last_name=Johnston&email=justin#myapi.com&company=MyApi
It's understandable to be confused, as is this is how you would get the data returned from an HTML form, and is quite a common way of sending variables via POST. However in this case you need to use JSON, which is why that won't work.

Using JSON in PHP to send data to Android

I'm not sure that the JSON codes i have used in my PHP is right to send the data to my Android App. My Android app works fine without any errors. I'm using Async Task to retrieve information from the server using JSON.
This is the code i have used in my Android app to get information from server :
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
myoutput = jObj.getString("stringpval");
I havn't displayed the entire code, but i'm sure that all the other codes work fine.
And below is my PHP script used to create a JSON array in PHP:
$a = array(
array('stringpval' => "My Value"));
print $json = json_encode($a);
So i have finished encoding json. I want my TextView in android to display "My Value"! Now when i run my android app and try to get the information from the server, my TextView goes blank. It is Null! What's the problem? Any Solution? Are the above codes correctly used?
The reason is that json_encode($a); is actually returning a JSONObject and not just a JSONArray as you're thinking.
What you're currently printing will look like this:
{
{
'stringpval' = "My Value"
}
}
I'm not sure why you're using a double-array for passing back a single value like that, so for now I would change your PHP file to:
$a = array('stringpval' => "My Value");
print $json = json_encode($a);
Which will return:
{
'stringpval' = "My Value"
}
Which you could then access in Java by:
JSONObject jObj = new JSONObject(result);
myoutput = jObj.getString("stringpval");
json usually is in two forms, either objects, or arrays, this is very important because you have to know which values are you retrieving from the server(json array or json object?) and hence parse them in the correct manner in the client side.
JsonArray are usually like this
{
"jsonarray_example": [
{
"id": "1",
"name": "android",
"description": "android 4.4.3 kitkat",
"updated_at": "0000-00-00 00:00:00"
} ,
{
"id": "2",
"name": "android",
"description": "android 4.1 jellybin",
"updated_at": "0000-00-00 00:00:00"
}
]
}
The opening and closing [] marks the array while the {} brackets marks the objects of the array called jsonarray_example but the brackets need not be like that now if your php page outputs something like that then you can retrieve the array else you have to retrieve the objects JsonObject in android
so from your problem above you are trying to retrieve jsonObjects while your response is array you should use something like
JsonArray result = new JsonArray() ;
JsonObject obj = //access the server files
result = obj.getJsonArray("stringpval") ;
// proceed extracting individual content from the response
for more check this LINK and this ONE can be really helpful

HTML is NULL in JSON object from json_encode

I have a ajax call calling a php file who runs a long php function which returns a JSON encoded array/object. Now I need to send HTML also into the ajax response. I thought about sending the HTML inside the array.
Is that a good practise?
Right now I cannot get it working, I get a NULL as value for that property. Don't know why.
$statHTML = '<table>';
foreach ($toHTML as $key=>$value) {
$statHTML.= '
<tr class="'.$key.'">
<td class="side">'.$value[0].'</td>
<td>'.$value[2].' '.$value[1].'</td>
</tr>';
}
$statHTML.= '</table>';
// echo $statHTML; // - this works
//function return
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => $statHTML
);
return json_encode($answer);
The ajax response from the console before the JSON.parse():
{
"mostSearched": {
"title": "Most serached houses",
"colNames": [21],
"rowNames": [2013],
"rows": [1]
},
"timeOfDay": {
"title": "Time of search",
"colNames": ["07:30"],
"rowNames": ["07:30"],
"rows": [
[1]
]
},
"mostSearchedDays": {
"title": "Most searched days",
"colNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rowNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rows": [
[1, 1, 1, 1, 1, 1, 1]
]
},
"statHTML": null
}
From php.net:
Parameters
value
The value being encoded. Can be any type except a resource.
All string data must be UTF-8 encoded.
So use:
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => utf8_encode($statHTML)
);
return json_encode($answer);
Most likely the build-in JSON parser used by PHP cannot properly parse the HTML, the easiest way to solve the issue is to base64 encode the html on the server, and then decode it on the client, using either the newer atob and btoa base64 methods, or one of the many polyfills out there.
use base64_enccode in this at the time of conversion
$answer = array('statHTML'=>base64_encode('<h1>html in here</h1>'));
echo json_encode($answer);exit;
And at the time of getting response from ajax
atob(response.statHTML);
Hope you understand how it works

Retrieve Json Decode Elements

I've tried a variety of things, but still have not been able to return username from the output below. How would I do this? I ran this line below and got the string below:
$work = exec($cmd);
var_dump($work);
$json_object = json_decode($work, true);
string(1118) "{"user"=>{"id"=>4151878, "username"=>"jerry_smithjerry", "firstname"=>"Jerry ", "lastname"=>"Smith", "birthday"=>nil, "sex"=>0, "city"=>nil, "state"=>nil, "country"=>nil, "registration_date"=>"2013-07-24T16:12:20-04:00", "about"=>"", "domain"=>"jerry_smithjerry.500px.com", "fotomoto_on"=>false, "locale"=>"en", "show_nude"=>false, "fullname"=>"Jerry Smith", "userpic_url"=>"/graphics/userpic.png", "upgrade_status"=>0, "store_on"=>false, "email"=>"jerry_smithjerry#aol.com", "upload_limit"=>20, "upload_limit_expiry"=>"2013-07-24T21:50:58-04:00", "upgrade_type"=>0, "upgrade_status_expiry"=>nil, "auth"=>{"facebook"=>0, "twitter"=>0}, "contacts"=>{}, "equipment"=>{}, "photos_count"=>0, "affection"=>0, "in_favorites_count"=>0, "friends_count"=>0, "followers_count"=>0, "not_active"=>true, "avatars"=>{"default"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "large"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "small"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "tiny"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}}}}" "
echo:
{"user"=>{"id"=>4151878, "username"=>"jerry_smithjerry", "firstname"=>"Jerry ", "lastname"=>"Smith", "birthday"=>nil, "sex"=>0, "city"=>nil, "state"=>nil, "country"=>nil, "registration_date"=>"2013-07-24T16:12:20-04:00", "about"=>"", "domain"=>"jerry_smithjerry.500px.com", "fotomoto_on"=>false, "locale"=>"en", "show_nude"=>false, "fullname"=>"Jerry Smith", "userpic_url"=>"/graphics/userpic.png", "upgrade_status"=>0, "store_on"=>false, "email"=>"jerry_smithjerry#aol.com", "upload_limit"=>20, "upload_limit_expiry"=>"2013-07-24T22:11:09-04:00", "upgrade_type"=>0, "upgrade_status_expiry"=>nil, "auth"=>{"facebook"=>0, "twitter"=>0}, "contacts"=>{}, "equipment"=>{}, "photos_count"=>0, "affection"=>0, "in_favorites_count"=>0, "friends_count"=>0, "followers_count"=>0, "not_active"=>true, "avatars"=>{"default"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "large"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "small"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "tiny"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}}}}
var_dump:
string(1118) "{"user"=>{"id"=>4151878, "username"=>"jerry_smithjerry", "firstname"=>"Jerry ", "lastname"=>"Smith", "birthday"=>nil, "sex"=>0, "city"=>nil, "state"=>nil, "country"=>nil, "registration_date"=>"2013-07-24T16:12:20-04:00", "about"=>"", "domain"=>"jerry_smithjerry.500px.com", "fotomoto_on"=>false, "locale"=>"en", "show_nude"=>false, "fullname"=>"Jerry Smith", "userpic_url"=>"/graphics/userpic.png", "upgrade_status"=>0, "store_on"=>false, "email"=>"jerry_smithjerry#aol.com", "upload_limit"=>20, "upload_limit_expiry"=>"2013-07-24T22:11:09-04:00", "upgrade_type"=>0, "upgrade_status_expiry"=>nil, "auth"=>{"facebook"=>0, "twitter"=>0}, "contacts"=>{}, "equipment"=>{}, "photos_count"=>0, "affection"=>0, "in_favorites_count"=>0, "friends_count"=>0, "followers_count"=>0, "not_active"=>true, "avatars"=>{"default"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "large"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "small"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "tiny"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}}}}"
Your json string doesn't have valid json, the json strings uses : as a key value separator, in your case you have used a php associative array like => notation. This json is not valid json,
according to this: json_decode returns string type instead of object You may be running json_encode() on a json string. json_encode() is used if you want to turn an object or array into json.
If you are doing something like $work = json_encode($json_string) somewhere before that code, that would be the cause. remove that line, run json_decode() on your original json string and it should be fine.
Once you flesh that out, you can do
$json_object = json_decode($your_json_string);
echo $json_object->user->username; //echo's the username

Categories