How do I get the country from this JSON string? [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Here's my string which I've captured from an API using CURL:
{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3860,-122.0838",
"org": "AS15169 Google Inc.",
"postal": "94040"
}
How do I get the country code? This is what I've been trying and it just returns the entire json string:
$json = json_decode($json_raw, true);
$country = $json['country'];

Since your value in in an object, use -> to access.
<?php
$a = '{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3860,-122.0838",
"org": "AS15169 Google Inc.",
"postal": "94040"
}';
$decode = json_decode($a);
echo $decode->country;// this line
See demo here
As Surace said, even this should work fine
<?php
$a = '{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3860,-122.0838",
"org": "AS15169 Google Inc.",
"postal": "94040"
}';
$decode = json_decode($a,true);
echo $decode['country'];
See demo here

as you decode json to php format it returns result as object so you have to use object syn text to access its properties.
replace
$decode = json_decode($a,true);
$country = $json['country'];
with
$decode = json_decode($a);
$country = $json->country;

I could be missing something but I see no reason for your code is not working for you.
You can use json_decode with the true option like you did to use the returned value as an array.
<?php
$json_raw = '{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3860,-122.0838",
"org": "AS15169 Google Inc.",
"postal": "94040"
}';
$json = json_decode($json_raw, true);
echo $country = $json['country'];
You can check here: https://eval.in/483744

Related

PHP fails to parse JSON - Unexpected Integer

I'm trying to make an application that will use a JSON input. Below is some code that shows the problem when run. The problem being a syntax error; unexpected integer from the "etag" line ("$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",). When I remove the etag line it runs fine but otherwise I get an error. Can I remove the etag line (not needed anyway) before being parsed or get around it some other way? I unfortunately cant change what the API sends.
<?php
$json = '{
"Form": {
"Id": "1",
"InternalName": "SignUp",
"Name": "Sign Up"
},
"$version": 7,
"$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",
"Email": "test#email.com",
"Phone": "(123) 412-3412",
"CarrierServiceProvider": "Sprint",
"WTSKeywords": "Testing WTS",
"WTBKeywords": "Testing WTB",
"Id": "1-3",
"Email_IsRequired": false,
"Phone_IsRequired": false,
"CarrierServiceProvider_IsRequired": true
}';
$data = json_decode($json);
echo $data->Email;
echo "\n";
echo $data->WTBKeywords;
?>
Code should output: test#email.com Testing WTB
You json string has both ' and ", so you cannot simple use single or double quoted.
Use heredoc like this,
$json = <<<EOT
{
"Form": {
"Id": "1",
"InternalName": "SignUp",
"Name": "Sign Up"
},
"$version": 7,
"$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",
"Email": "test#email.com",
"Phone": "(123) 412-3412",
"CarrierServiceProvider": "Sprint",
"WTSKeywords": "Testing WTS",
"WTBKeywords": "Testing WTB",
"Id": "1-3",
"Email_IsRequired": false,
"Phone_IsRequired": false,
"CarrierServiceProvider_IsRequired": true
}
EOT;
$data = json_decode($json);
echo $data->Email;
echo "\n";
echo $data->WTBKeywords;

PHP 7.2 json_decode()

I have this string that was working with json_decode() with PHP 5.6 but doesn't work with PHP 7.2?
$json = '
{
"text": "Hi {{fname}}
Welcome to our customer support.
Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}';
I have tried replacing the whitespaces and newline like this
$json = preg_replace("/\n/m", '\n', $json);
$what = "\\x00-\\x19"; // all whitespace characters except space itself
$json = trim(preg_replace( "/[".$what."]+/" , '' , $json));
Which results into a string like this
\n{\n "text": "Hi {{fname}} \n Welcome to our customer support. \n Please select language to proceed",\n "buttons": [\n {\n "text": "English",\n "value": "language_english",\n "type": "postback"\n },\n {\n "text": "Germany",\n "value": "language_germany",\n "type": "postback"\n }\n ]\n}
Notice the \n in between and outside double quotes which makes it an invalid json and hence json_decode won't work in this case.
Does anyone know a way to achieve this?
Thank you.
{
"text": "Hi {{fname}} \n Welcome to our customer support. \n Please select language to proceed",
"buttons": [{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}
This is a valid json. i added line breaks so you can use them if you want to print the messages in browser.
You can use this nice tool to validate your json when you have doubts.
Editing my answer based on comment feedback.
First of all the right step is that you figure out why you have a broken json in the database. If it's not on you and you have to fix it in php then a solution could be like this:
<?php
echo '<pre>';
$data = '
{
"text": "Hi {{fname}}
Welcome to our customer support.
Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}';
if (strstr($data, "\n")) {
$data = trim(preg_replace('/\s\s+/', ' ', $data));
}
echo $data;
Above code will capture the line breaks of your text field, and replace them with DOUBLE space. Then you will get a valid json like:
{
"text": "Hi {{fname}} Welcome to our customer support. Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}
What you can do if you need the line breaks is that you decode your json (just like you want and replace the double spacing in text field with a line break

json_encode() issue and storing in cookie issue in PHP

When I am converting json_encode; It is converting it in correct format, but when I am storing it in cookie; format get changed. I want to store in cookie as it is.
JSON STRING:
{
"ID": "0",
"basicAddress": {
"ID": "0",
"Line1": "327 S Main St",
"Line2": "",
"Line3": "",
"City": "Fitzgerald",
"ZipCode": "31750",
"StateProv": "",
"Country": "",
"stateProv": "GA"
},
"Name": "",
"Latitude": "31.7114886",
"Longitude": "-83.25471970000001",
"IsPreferred": "false"
}
AFTER STORING IN COOKIE:
%7B%22ID%22%3A%220%22%2C%22basicAddress%22%3A%7B%22ID%22%3A%220%22%2C%22Line1%22%3A%22327+S+Main+St%22%2C%22Line2%22%3A%22%22%2C%22Line3%22%3A%22%22%2C%22City%22%3A%22Fitzgerald%22%2C%22ZipCode%22%3A%2231750%22%2C%22StateProv%22%3A%22%22%2C%22Country%22%3A%22%22%2C%22stateProv%22%3A%22GA%22%7D%2C%22Name%22%3A%22%22%2C%22Latitude%22%3A%2231.7114886%22%2C%22Longitude%22%3A%22-83.25471970000001%22%2C%22IsPreferred%22%3A%22false%22%7D
I found solution and it's working absolutely correct as i want
$address={
"ID": "0",
"basicAddress": {
"ID": "0",
"Line1": "327 S Main St",
"Line2": "",
"Line3": "",
"City": "Fitzgerald",
"ZipCode": "31750",
"StateProv": "",
"Country": "",
"stateProv": "GA"
},
"Name": "",
"Latitude": "31.7114886",
"Longitude": "-83.25471970000001",
"IsPreferred": "false"
};
cookie_expire_time=30000;
header("Set-Cookie: address=$address; Domain=.example.com;Path=/; Max-Age=".cookie_expire_time.";");
It is correct behaviour for setcookie to URL-encode the value. You can use setrawcookie to avoid that automatic encoding, but then you need to ensure yourself that your cookies are correctly formed to be HTTP compliant.

Get phone type and carrier using Twilio Phone Validator Curl command

I am trying to get specific data from Twilio's Phone Validator curl command:
$cmd='curl -XGET "https://lookups.twilio.com/v1/PhoneNumbers/5551234321'?Type=carrier&Type=caller-name" -u "{AccountSid}:{AuthToken}" ';
exec($cmd,$result);
When I print_r the result, I get an array.
echo '<pre>'; print_r($result); '</pre>';
Array
(
[0] => {"caller_name": {"caller_name": "JOHN SMITH", "caller_type": "CONSUMER", "error_code": null}, "country_code": "US", "phone_number": "+5551234321", "national_format": "(555) 123-4321", "carrier": {"mobile_country_code": "310", "mobile_network_code": "120", "name": "Sprint Spectrum, L.P.", "type": "mobile", "error_code": null}, "add_ons": null, "url": "https://lookups.twilio.com/v1/PhoneNumbers/+5551234321?Type=carrier&Type=caller-name"}
)
How can I get specific values as PHP variables?
e.g. "name": "Sprint Spectrum, L.P.", "type": "mobile"
as:
$name = "Sprint Spectrum, L.P.";
$type = "mobile";
I tried:
foreach ($result->items as $item) {
var_dump($item->carrier->name);
}
But get an error: Invalid argument supplied for foreach()
Thank you #EatPeanutButter and #Julqas for your assistance. Pointed me in the right direction.
Working code:
$json = json_decode($result[0],true);
$type = $json['carrier']['type'];
$carrier = $json['carrier']['name'];

file_get_contents not getting json

I have the PHP which should get the JSON object from the postcodes api (http://postcodes.io/) however it does not seem to be working.
if(isset($_POST["postcode"])){
$json = file_get_contents('api.postcodes.io/postcodes/'.$_POST["postcode"]);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["status"];
}
the $json_data["status"]; does not echo anything.
for example when $_POST["postcode"] equals "IP12 2UH" the below should be returned:
{
"status": 200,
"result": {
"postcode": "IP12 2UH",
"quality": 1,
"eastings": 633715,
"northings": 253024,
"country": "England",
"nhs_ha": "East of England",
"longitude": 1.41299500121177,
"latitude": 52.126073695307,
"parliamentary_constituency": "Suffolk Coastal",
"european_electoral_region": "Eastern",
"primary_care_trust": "Suffolk",
"region": "East of England",
"lsoa": "Suffolk Coastal 007G",
"msoa": "Suffolk Coastal 007",
"nuts": null,
"incode": "2UH",
"outcode": "IP12",
"admin_district": "Suffolk Coastal",
"parish": "Suffolk Coastal",
"admin_county": "Suffolk",
"admin_ward": "Rendlesham",
"ccg": "NHS Ipswich and East Suffolk",
"codes": {
"admin_district": "E07000205",
"admin_county": "E10000029",
"admin_ward": "E05007216",
"parish": "E04009449",
"ccg": "E38000086"
}
}
}
You need to add http:// in the url

Categories