I want to remove double quotes from json data object.
i have tried many ways but still my numeric is showing in double
quotes.
here is my code ..
<?php
$m_nu= str_replace('"', ' ', $mobile_number);
$skt1['mobile_number'] = str_replace('"', " ", json_encode($mobile_number, JSON_HEX_APOS));
?>
it's given output like
<?php
{
"status": true,
"message": "Profile updated successfully.",
"data": [
{
"user_id": 11,
"Email": "make_jackson#gmail.com",
"first_name": "make",
"last_name": "Jackson",
"mobile_number": "9856898998",
"user_image": ""
}
]
}
?>
and i want like
<?php
{
"status": true,
"message": "Profile updated successfully.",
"data": [
{
"user_id": 11,
"Email": "make_jackson#gmail.com",
"first_name": "make",
"last_name": "Jackson",
"mobile_number": 9856898998,
"user_image": ""
}
]
}
?>
when i tried string to number by using
<?php (int)$mobile_number;?>
it's working good but problem is original value are changed and output
given like below.
<?php
{
"status": true,
"message": "Profile updated successfully.",
"data": [
{
"user_id": 11,
"Email": "make_jackson#gmail.com",
"first_name": "make",
"last_name": "Jackson",
"mobile_number": 2147483647,
"user_image": ""
}
]
}
?>
My mobile number value are changed original value is 9856898998
and it's return 2147483647.
Type (float) instead of (int), The int's max value is 2147483647 and you can't use int higher then that number... so you can Just use float...
Related
I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.
I'm trying to use JSON in PHP and I got stucked. I'm new in this, please, if you can help me with that.
I want to display content from "list" from the code below (For example list, name and/or frags).
{
"status": true,
"hostname": "{IP}",
"port": {PORT},
"queryPort": {PORT},
"name": "Cod2 Server",
"map": "mp_genesisarc",
"secured": true,
"password_protected": false,
"version": "1.3",
"protocol": "udp",
"players": {
"online": 1,
"max": "28",
"list": [
{
"frags": "1",
"ping": "54",
"name": "Mr Anderson"
}
]
},
"cached": false
}
This is the code I use (Doesn't work):
<?php
$serverip = "localhost";
$info = json_decode( file_get_contents( 'https://use.gameapis.net/cod2/query/info/000.000.00.0:0000'.$serverip ), true );
if(!$info['status']) {
echo 'Offline';
} else {
echo $info['players']['list']['name'];
}
?>
Thanks in advance,
Jim.
$info['players']['list'][0]['name']
This will get you desired element. Try outputting $info next time to find this error yourself.
Try using a foreach loop. It's cleaner when iterating an array.
<?php
$serverip = "localhost";
$info = json_decode( file_get_contents( 'https://use.gameapis.net/cod2/query/info/000.000.00.0:0000'.$serverip ), true );
if(!$info['status']) {
echo 'Offline';
}
else {
foreach ($info['players']['list'] as $player) {
echo $player['name'];
}
}
?>
list will you number of online users records so there may be single or multiple users so you have to go through the loop and can display all the records available in the list. Add for loop to your code instead of displaying single record with index.
if(count($info['players']['list']) > 0){
for($cnt = 0; $cnt < count($info['players']['list']); $cnt++){
echo $info['players']['list'][$cnt]['name'];
}
} else {
echo "Write your message";
}
Took the following array (I had to change few things) and go here . Paste the array at the left side, then press the right arrow and see at the right side the analysis of your array. Open the tree view and you will realize that there is a 0 index in the list. So you can not access what you want by doing echo $info['players']['list']['name']; but you need to apply the index 0 of the list echo $info['players']['list'][0]['name'];
[{
"status": true,
"hostname": "{IP}",
"port": 555,
"queryPort": 555,
"name": "Cod2 Server",
"map": "mp_genesisarc",
"secured": true,
"password_protected": false,
"version": "1.3",
"protocol": "udp",
"players": {
"online": 1,
"max": "28",
"list": [
{
"frags": "1",
"ping": "54",
"name": "Mr Anderson"
}
]
},
"cached": false
}]
If you paste your json string into https://jsonlint.com/ and click Validate JSON, you will see that you have a couple of syntax errors; namely the values for port and queryPort.
When they are corrected, you should have something like this:
{
"status": true,
"hostname": "{IP}",
"port": "{PORT}",
"queryPort": "{PORT}",
"name": "Cod2 Server",
"map": "mp_genesisarc",
"secured": true,
"password_protected": false,
"version": "1.3",
"protocol": "udp",
"players": {
"online": 1,
"max": "28",
"list": [{
"frags": "1",
"ping": "54",
"name": "Mr Anderson"
}]
},
"cached": false
}
Now that the json is fixed, you can convert it to an array for simple processing.
Code: (Demo)
$serverip="localhost";
$array=json_decode(file_get_contents( 'https://use.gameapis.net/cod2/query/info/000.000.00.0:0000'.$serverip),true);
if(!isset($array['status']) || $array['status']===false){
echo 'Offline';
}else{
foreach($array['players']['list'] as $players){
echo "<div>Name: {$players['name']}, Frags: {$players['frags']}, Ping: {$players['ping']}</div>\n";
}
}
foreach() is a better/cleaner practice than resorting to for() which will unfortunately require count(), and a "counter" variable, and incrementation.
I have an URL that returns the JSON object below:
{
"addressList": {
"addresses": [
{
"id": 0000000,
"receiverName": "Name Example",
"country": {
"id": "BRA",
"name": "Brasil"
},
"state": {
"id": "SP"
},
"city": "São Paulo",
"zipcode": "00000000",
"type": "Residential",
"street": "000, St Example",
"number": 00,
"neighborhood": "Example",
"hash": "1bf09357",
"defaultAddress": false,
"notReceiver": false
}
]
}
}
I want to get the state value, how can I retrieve that with PHP?
I tried, something like this, but I couldn't get the state value, that should be SP in this case.
$string = '{ "addressList": { "addresses": [ { "id": xxxxxx, "receiverName": "XXXXX XXXXX", "country": { "id": "BRA", "name": "Brasil" }, "state": { "id": "SP" }, "city": "São Paulo", "zipcode": "03164xxx", "type": "Residential", "street": "Rua xxx", "number": xx, "neighborhood": "xxxxx", "hash": "xxxxx", "defaultAddress": false, "notReceiver": false } ] } }';
$json_o = json_decode($string);
$estado = $json_o->state;
How can I achieve the result I want?
Your JSON is not valid - you can validate it on jsonlint.com (it's invalid due to incorrectly formatted numeric values - "id" : 000000).
From then on, you can decode the value and access your data:
$json_o = json_decode($string);
$estado = $json_o->addressList->addresses[0]->state->id;
If you don't have access to the code that generates the JSON, you can attempt to run a regex to match, replace & wrap the numerical values with ":
$valid_json = preg_replace("/\b(\d+)\b/", '"${1}"', $str);
Note: The above is just an example - you'll have to figure out a case where a numerical value is already wrapped by ".
Your JSON has a couple of syntax errors:
"id": 0000000
"number": 00
JSON doesn't support leading zeros. If precise formatting is important, use strings:
"number": "00"
"id": "0000000"
Alternatively, use well-formed integers in the JSON (saves space) and convert them to formatted strings in PHP.
Once you've fixed your JSON, you can access the state->id value of the first address as I do below. When you decode JSON from an untrusted source, be prepared to do some error handling:
$json_string ="..."; //your source, to be decoded
$json_o= json_decode($json_string);
if(is_null($json_o)): //there was an error decoding
$errno = json_last_error();
$err_msg = json_last_error_msg();
die("Json decode failed: Error #$errno: $err_msg");
endif;
//we get here if json_decode succeeded. To get "SP", do...
$stateID = $json_o->addressList->addresses[0]->state->id;
Try:
$json_o = json_decode($string, true);
$estado = $json_o['addressList']['addresses'][0]['state']['id'];
I was wondering how to extract only a certain part from a JSON String:
[
{
"ID": "132",
"countrycode": "DE",
"USERNAME": "CRC Titan2000",
"Nickname": "^7[6S] ^1Titan",
"Money": "550111",
"Distance": "105692714",
"Trip": "370839",
"Bonus": "223",
"Last Car": "RB4",
"Last Position": "The Hills",
"Server": "^7One"
},
{
"ID": "1634",
"countrycode": "ES",
"USERNAME": "lobocop",
"Nickname": "^4Leo ^1Messi",
"Money": "12816",
"Distance": "17091463",
"Trip": "25682",
"Bonus": "29",
"Last Car": "MRT",
"Last Position": "Bridge East",
"Server": "^7One"
},
{
"ID": "4240",
"countrycode": "GB",
"USERNAME": "Smacky",
"Nickname": "^7^d^6o^7^s",
"Money": "-532",
"Distance": "1987579",
"Trip": "7738",
"Bonus": "51",
"Last Car": "RB4",
"Last Position": "The Hills",
"Server": "^7One"
},
{
"ID": "5467",
"countrycode": "TR",
"USERNAME": "excaTR",
"Nickname": "^1Furkan^7Tr",
"Money": "7363",
"Distance": "17064283",
"Trip": "15747",
"Bonus": "31",
"Last Car": "RB4",
"Last Position": "Bridge East",
"Server": "^7One"
}
]
I only want to pull the "Last Position" of the "USERNAME" excaTR, but ignore all the others. Sort of like a MySQL query, where I want to echo the last position WHERE username='excaTR', but instead for PHP and JSON.
This is the code that I tried, but it didn't work
$json_stats = file_get_contents('<JSON string here>');
$stats_data = json_decode($json_stats, true);
foreach ($stats_data as $_SESSION['username'] => $location){
echo $location['Last Position'];
}
You are not using foreach as it should be.
Have a look at your JSON, you have an array of objects.
So you have to iterate over you array, and check your object values.
By the way, in my answer, I use json_decode( ,false) to force result as a multidimensional array, matter of taste only.
$json_stats = file_get_contents('<JSON string here>');
$stats_data = json_decode($json_stats, false);
foreach ($stats_data as $array) {
if ($array['USERNAME'] == 'excaTR') {
echo $array['Last Position'];
}
}
I would like to know how to count how many people follows someone in Instagram and place the number in a var, Instagram gives you this link:
https://api.instagram.com/v1/users/3/followed-by?access_token=xxxxxxxxx.xxxxxxxxxxxxxxxxxxxx
And displays a result like so
{
"data": [{
"username": "meeker",
"first_name": "Tom",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_6623_75sq.jpg",
"id": "6623",
"last_name": "Meeker"
},
{
"username": "Mark",
"first_name": "Mark",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_29648_75sq_1294520029.jpg",
"id": "29648",
"last_name": "Shin"
},
{
"username": "nancy",
"first_name": "Nancy",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_13096_75sq_1286441317.jpg",
"id": "13096",
"last_name": "Smith"
}]
}
How can I count how many are there and place it in a var, lets say:
<? echo "You are been follow by ".$followers." users!"; ?>
To display: You are been follow by 3 users!
You would need to use json_decode to to decode the JSON response, then access the resulting object's data attribute (an array of 'follower' objects), and count that:
$json = '{
"data": [{
"username": "meeker",
"first_name": "Tom",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_6623_75sq.jpg",
"id": "6623",
"last_name": "Meeker"
},
{
"username": "Mark",
"first_name": "Mark",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_29648_75sq_1294520029.jpg",
"id": "29648",
"last_name": "Shin"
},
{
"username": "nancy",
"first_name": "Nancy",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_13096_75sq_1286441317.jpg",
"id": "13096",
"last_name": "Smith"
}]
}';
$json = json_decode($json);
echo "You have " .count($json->data) ." followers"
OR
$json = json_decode($json,true);
echo "You have " .count($json['data']) ." followers"
You are getting as a json string, you need to decode it using json_decode.
$data = json_decode($string,true);
$followers = count($data['data']);
CodePad Demo.
You need to use json_decode() which will return you a PHP array. Then all you need to do is to count() all the values in the array with 'data' key.
You can use json_decode
$array = json_decode($str);
Then give
echo count($array);
It will give total count of users
simple way to count entries returned asJSON
echo count(json_decode($followers);
Use json_decode() to create a PHP array from the JSON. Then you can simply do a count() on that:
$jsonData = json_decode($yourAPIResult);
echo count($jsonData->data);
Be aware, however, that you probably should set up some error handling in case the API did not return a proper JSON string. So something like this might be better:
if (is_null($jsonData) || !property_exists($jsonData, 'data')) {
echo '?';
} else {
echo count($jsonData->data);
}