i'm using PHP and i want to get some date from a json FILE ,
this what i have this file
{
"Contacts": [{
"nataliya.mayk#ut-gr.com": {
"ContactID": "3367870013932183",
"First Name": "",
"Last Name": "maydanyuk",
"Title": "",
"full Name": "maydanyuk",
"Mobile": "",
"num": 0,
"num2": 200
}
}, {
"sebsfsgilbedsdfsdrt045#orsfsefange.fr": {
"ContactID": "336787000013037828",
"First Name": "J\u00e9r\u00f4me",
"Last Name": "Sommet",
"Title": "Directeur Commeqsdqdrcial Retail France, membre du CODIR",
"full Name": "J\u00e9r\u00f4me Sommet",
"Mobile": "",
"num": 6,
"num2": 1600
}
}]
}
so i should first use
$str = file_get_contents('/theFileThatContainsJSON.json');
now i want to access to the the ContactID Of email nataliya.mayk#ut-gr.com , how can i do it ?, i want not to to use loops , because the file will be too big.
i want something like that
echo $str->Contacts->nataliya.mayk#ut-gr.com->ContactID ;
or
echo $str['Contacts']['nataliya.mayk#ut-gr.com']['ContactID'] ;
i tried all of them but not working , as i said before i want to access directly , because i want to get infromations for specific mail .
thanks
this is not working also
why this is not working , i used the same format
$str = file_get_contents('http://freelance-day.eu/zohocontacts.json');
$array = json_decode($str, true);
echo $array['Contacts'][0]['frejus#autoecole-inris.com']['ContactID'];
Try to decode the JSON and structure
$str = file_get_contents('/theFileThatContainsJSON.json');
$str_arr = json_decode($str, true);
echo $str_arr['Contacts']['nataliya.mayk#ut-gr.com']['ContactID']
Related
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;
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
I am receiving data from a webhook with the following code below.
<?php
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
$myfile = fopen("callback.txt", "a") or die("Unable to open file!");
$txt = $input["payload"]["type"];
fwrite($myfile, "\n". $txt);
fclose($myfile);
http_response_code(200);
?>
I am trying to get the 'type' value from the retuned output. I have found that using an if statement inside a for each loop would do the job. However i'm sure this isn't an ideal solution. is there a more direct way of getting that element?
The code above is outputting an empty text file.
and the documentation shows the json should be in the following format:
{
"action": "add",
"collection": "broadcast",
"payload": {
"author": "Sveninge Bambuser",
"created": 1474033783,
"customData": "",
"height": 540,
"id": "9353eaec-794f-11e6-97c0-f19001529702",
"ingestChannel": "cfc8626c-9a0e-ab78-6424-3eb0978d8e45",
"lat": 63.205312,
"length": 0,
"lon": 17.13011,
"positionAccuracy": 25,
"positionType": "GPS",
"preview": "https://archive.bambuser.com/9353eaec-794f-11e6-97c0-f19001529702.jpg",
"resourceUri": "https://cdn.bambuser.net/broadcasts/9353eaec-794f-11e6-97c0-f19001529702?da_signature_method=HMAC-SHA256&da_id=9353eaec-794f-11e6-97c0-f19001529702&da_timestamp=1474033783&da_static=1&da_ttl=0&da_signature=eaf4c9cb29c58b910dcbad17cf7d8a3afa4e6a963624ba4c4fd0bb5bade1cdd6",
"tags": [
{
"text": "whoa"
}
],
"title": "Amazing!",
"type": "live",
"width": 960
},
"eventId": "93df93061a891c23"
}
I replaced:
$txt = $input["payload"]["type"];
with:
$txt = $input['payload']['type'];
it appears to be the double quotes causing the issue.
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'];
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