Get Json Object from external URL with PHP - php

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'];

Related

get array content from json (telegram api) in php

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.

Getting data from nested arrays in json with php

I have my json from a url feed. Here's a sample below. I'm not doing the foreach loop correctly is the problem
{
"useLive": true,
"models": [
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"id": 5293074,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu7",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model1",
"languages": ["en"],
"stripScore": 998.5,
"token": "93021860dbebd5ba27e604f6b4b93754"
},
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"id": 6492104,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu8",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model2",
"languages": [],
"stripScore": 997.25,
"token": "2c6ee95270f6faf76cd33321732136e3"
}
],
"ttl": 15,
"tagType": "F+T",
"tagName": "Featured",
"defaultTags": [
{
"name": "whatever1",
"url": "/tags/whatever1"
},
{
"name": "whatever2",
"url": "/tags/whatever2"
},
{
"name": "whatever3",
"url": "/tags/whatever3"
}
],
"serverTime": "2018-09-26T14:23:00Z"
}
Here's my php code so far. I've tried quite a few different things. I normally use xml feeds which seem to be easy for me to setup for what I need. I'm not sure what I'm missing here.
$url = 'https://whatever.com/api/external/v4/widget?userId=whatever&tag=featured'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$performers = json_decode($data, true); // decode the JSON feed
foreach ($performers as $performer) {
$info = $performer[0]["username"];
echo $info;
}
I'm only getting the first username and then error messages.
Warning: Illegal string offset 'username' in /whatever
Can anyone help with this?
You should use $performers['models'] array in foreach and then get username it will work fine try the following code
$performers = json_decode($data, true);
if(isset($performers['models'])){
foreach ($performers['models'] as $performer) {
$info = (isset($performer["username"])) ? $performer["username"] : '';
echo $info;
echo "<br>";
}
}
Output
model1
model2

How to remove double quotes from json array data object

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...

json_decode does not return array in php

I am facing with a problem, when I am trying to parse json returns from server into array in php. Here is my code ...
<?php
mb_internal_encoding('UTF-8');
$url = 'http://localhost/busexpress/api/v1/mobile_user_register/mobile_user_register/retrieve.json';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
//$data="'".$data."'";
echo $data;
curl_close($ch);
//$trimspace = preg_replace('/\s+/', '', $data);
//echo $trimspace;
$jdata = json_decode($data, true);
print_r $jdata;
?>
This is the json after trimming space. I also want to convert it int array with json_decode() but no result return. I think this json is valid. And suggestion pls. This is my firstly trying to feed web service from server.
Thanks
'{
"status": "1",
"user": [
{
"id": "27",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "0d08ed",
"deposit": "0",
"created": "2015-06-0316:35:08",
"updated": "1110-11-3000:00:00",
"status": "0"
},
{
"id": "28",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "fb4876",
"deposit": "0",
"created": "2015-06-0316:37:14",
"updated": "1000-01-0100:00:00",
"status": "0"
}
]
}'
----------Edit---------
As your suggestion I comment trimming space and correct json format. And echo $data; .....
{
"status": "1",
"user": [
{
"id": "27",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "0d08ed",
"deposit": "0",
"created": "2015-06-0316:35:08",
"updated": "1110-11-3000:00:00",
"status": "0"
},
{
"id": "28",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "fb4876",
"deposit": "0",
"created": "2015-06-0316:37:14",
"updated": "1000-01-0100:00:00",
"status": "0"
}
]
}
In decoding array doesn't have any data.
$jdata = json_decode($data, true);
print_r $jdata;
echo "user status -> ". $jdata["status"];
when I copy that json and hard code in a string, decode it again, it works for me. please see my testing code....
$data =' {"status":"1","mobile_user":[{"id":"1","name":"saa","phone_no":"09978784963","activate_code":"","deposit":"0","created":"2015-05-29 00:00:00","updated":"0000-00-00 00:00:00","status":"1"},{"id":"3","name":"ttr","phone_no":"090930499","activate_code":"","deposit":"0","created":"2015-06-01 00:00:00","updated":"0000-00-00 00:00:00","status":"0"}]}';
$data = json_decode($data,true);
$status = $data['status'];
$mobile_user = $data['mobile_user'];
$id = $mobile_user[0]["id"];
$name = $mobile_user[0]["name"];
echo "id -> ". $id ."<br>";
echo "name -> ". $name;
Any suggestion pls!
I think your json is malformed. Remove $data="'".$data."'";
You can check json error if any.
And $trimspace = preg_replace('/\s+/', '', $data); is needless.
json_decode usually returns an object, so I don't think your code is wrong here.
$arrayObject = new ArrayObject($object);
$array = $arrayObject->getArrayCopy();
This is how you can convert it to an array. It works in PHP 5.3+
Try this
$jdata = json_decode($trimspace, true);
print_r($jdata);
First of all your json is malformed. Remove the '' from the beginning and the end of your file. The contents of $data should look like this:
{
"status": "1",
"user": [
{
"id": "27",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "0d08ed",
"deposit": "0",
"created": "2015-06-0316:35:08",
"updated": "1110-11-3000:00:00",
"status": "0"
},
{
"id": "28",
"name": "kktt",
"phone_no": "1239293",
"activate_code": "fb4876",
"deposit": "0",
"created": "2015-06-0316:37:14",
"updated": "1000-01-0100:00:00",
"status": "0"
}
]
}
Second $jdata is an associative array. You cannot print its contents with echo. Instead do
print_r($jdata);
Third you don't need to remove spaces. Do that in the script that produces the json, otherwise just parse the json with the spaces directly.

how to loop through a Json responce

I have web page which get Json responce like this
{
'hotel_1page':[
{
'id':'10',
'name':'fsf',
'telephone':'233333'
},
{
'id':'11',
'name':'setttttt',
'telephone':'213123123'
},
{
'id':'12',
'name':'fsdfsdf',
'telephone':'122212121'
},
{
'id':'13',
'name':'xxcvcxv',
'telephone':'2147483647'
},
{
'id':'14',
'name':'dssdfg',
'telephone':'2147483647'
},
{
'id':'15',
'name':'dfsdfsdf',
'telephone':'21312321'
},
{
'id':'16',
'name':'fx_test_nw1',
'telephone':'23232323'
},
{
'id':'17',
'name':'fx_test_nw2',
'telephone':'31313131'
}
]
}
and i want to loop through this data and get this data to array and display as html how can i achieve this
this is where i get get json responce,and when i var_dump json encoded variable it says null,where $json variable shows the json responce,
$json = file_get_contents('http://www.example.com/hotel_list.php');
var_dump($json);
$array = json_decode($json, true);
var_dump($array);
The json that you are trying to parse is invalid. Change the single quotes to double quotes and you should be able to parse it to an array.
The JSON documentation says
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
This should work:
$json = '{ "hotel_1page": [ { "id": "10", "name": "fsf", "telephone": "233333" }, { "id": "11", "name": "setttttt", "telephone": "213123123" }, { "id": "12", "name": "fsdfsdf", "telephone": "122212121" }, { "id": "13", "name": "xxcvcxv", "telephone": "2147483647" }, { "id": "14", "name": "dssdfg", "telephone": "2147483647" }, { "id": "15", "name": "dfsdfsdf", "telephone": "21312321" }, { "id": "16", "name": "fx_test_nw1", "telephone": "23232323" }, { "id": "17", "name": "fx_test_nw2", "telephone": "31313131" } ] }';
echo '<pre>';
var_dump(json_decode($json, true));
echo '</pre>';
I replaced all single quotes with double quotes, that did the trick.
I used single quotes before which caused json_decode to return null
[Edit for usage]
To use the data, you could use something like this:
$obj = json_decode($json, true);
foreach($obj as $row)
{
foreach($row as $key => $item)
{
// $item['id']
// $item['name']
// $item['telephone']
}
}
I'm using a nested foreach() because the id, name and telephone are an array within the hotel_page1 array

Categories