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;
Related
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
Using smsgateway.me to send a message I use the default code with my own variables which are working fine. However, sometimes the SMS does not send and I would like to store the SMS in the database if failed.
To do so I think I need a value from the $result array, but I dont know how to start. I tried many different codes without any result.
Can anywone please tell me how to get an if sent ok -> do something / else do something else based on the code and variables below?
Thanks a lot!
Documentation here
Here is the default code (with default variables) that sends a message:
<?php
include "smsGateway.php";
$smsGateway = new SmsGateway('demo#smsgateway.me', 'password');
$deviceID = 1;
$number = '+44771232343';
$message = 'Hello World!';
$options = [
'send_at' => strtotime('+10 minutes'), // Send the message in 10 minutes
'expires_at' => strtotime('+1 hour') // Cancel the message in 1 hour if the message is not yet sent
];
//Please note options is no required and can be left out
$result = $smsGateway->sendMessageToNumber($number, $message, $deviceID, $options);
?>
Success content:
{
"success": true,
"result": {
"success": [
{
"id": "308",
"device_id": "4",
"message": "hello world!",
"status": "pending",
"send_at": "1414624856",
"queued_at": "0",
"sent_at": "0",
"delivered_at": "0",
"expires_at": "1414634856",
"canceled_at": "0",
"failed_at": "0",
"received_at": "0",
"error": "None",
"created_at": "1414624856",
"contact": {
"id": "14",
"name": "Phyllis Turner",
"number": "+447791064713"
}
}
],
"fails": [
]
}
}
error content:
{
"success": true,
"result": {
"success": [
],
"fails": [
"number": "+44771232343"
"message": "hello world!",
"device": 1
"errors": {
"device": ["The selected device is invalid"],
}
]
}
}
This did the trick if failed:
if (isset($result['response']['result']['fails'][0]['number']) === TRUE) {
echo 'failed';
else{
echo 'success';
}
this works on success:
if(isset($result['response']['result']['success'][0]['id']) === TRUE){
echo 'success';
}else{
echo 'failed';
}
Thanks Michael, your reply helped me to change it a bit and figure it out!
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 been trying to call a JSON feed using PHP the code I have used so far is
$json = file_get_contents( 'http://football-api.com/api/?Action=standings&APIKey=********' );
$team_data = json_decode($json);
<?php
echo $team_data->teams[0]->stand_team_name;
echo $team_data->teams[1]->stand_team_name;
echo $team_data->APIRequestsRemaining;
?>
However the first 2 echos don't work but the 3rd one does...
A snippet from the API...
{
APIVersion: 1,
APIRequestsRemaining: 1000,
DeveloperAuthentication: "TRUE",
teams: [
{
stand_id: "12049092",
stand_competition_id: "1204",
stand_season: "2014/2015",
stand_round: "29",
stand_stage_id: "12041081",
stand_group: "",
stand_country: "England",
stand_team_id: "9092",
stand_team_name: "Chelsea",
stand_status: "same",
stand_recent_form: "DWDWW",
stand_position: "1",
stand_overall_gp: "28",
stand_overall_w: "19",
stand_overall_d: "7",
stand_overall_l: "2",
stand_overall_gs: "58",
stand_overall_ga: "23",
stand_home_gp: "14",
stand_home_w: "11",
stand_home_d: "3",
stand_home_l: "0",
stand_home_gs: "28",
stand_home_ga: "6",
stand_away_gp: "14",
stand_away_w: "8",
stand_away_d: "4",
stand_away_l: "2",
stand_away_gs: "30",
stand_away_ga: "17",
stand_gd: "35",
stand_points: "64",
stand_desc: "Promotion - Champions League (Group Stage)"
},
Any ideas why it is not showing up?
Your request may not return a result for stand_team_name because the API you are calling requires a comp_id parameter which isn't shown in the API call you indicate you are making.
From the documentation, the API you are calling requires a competition id as shown below:
http://football-api.com/api/?Action=standings&APIKey=[YOUR_API_KEY]&comp_id=[COMPETITION]
Documentation: http://football-api.com/documentation/#Standings
Not adding the comp_id results in the following error response:
{"APIVersion":1,"APIRequestsRemaining":999,"DeveloperAuthentication":"TRUE","Action":"standings","Params":{"Action":"standings","APIKey":"xxxxxx"},"ComputationTime":0.0018100738525391,"IP":"xxxxxx","ERROR":"You have not entered the competition id, please use the parameter comp_id","ServerName":"Football-API","ServerAddress":"http:\/\/football-api.com\/api"}
For testing purposes, use comp_id=1204 as shown in the documentation and try changing your code to the following which works for me:
$json = file_get_contents( 'http://football-api.com/api/?Action=standings&APIKey=********&comp_id=1204');
Here's a complete example that works for me:
<?
$api_key = 'xxxxxx';
$json = file_get_contents( 'http://football-api.com/api/?Action=standings&APIKey=' . $api_key .'&comp_id=1204');
$team_data = json_decode($json);
print_r($team_data) . "\n";
echo $team_data->teams[0]->stand_team_name . "\n";
echo $team_data->APIRequestsRemaining . "\n";
?>
In GitLab web hooks this is the json they give as an example.
{
"before": "95790bf891e76fee5e1747ab589903a6a1f80f22",
"after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"ref": "refs/heads/master",
"user_id": 4,
"user_name": "John Smith",
"project_id": 15,
"repository": {
"name": "Diaspora",
"url": "git#localhost:diaspora.git",
"description": "",
"homepage": "http://localhost/diaspora",
},
"commits": [
{
"id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
"message": "Update Catalan translation to e38cb41.",
"timestamp": "2011-12-12T14:27:31+02:00",
"url": "http://localhost/diaspora/commits/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
"author": {
"name": "Jordi Mallach",
"email": "jordi#softcatala.org",
}
},
{
"id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"message": "fixed readme",
"timestamp": "2012-01-03T23:36:29+02:00",
"url": "http://localhost/diaspora/commits/da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"author": {
"name": "Code Solution dev user",
"email": "gitlabdev#dv6700.(none)",
},
},
],
"total_commits_count": 4,
}
I've placed this in a file test.json.
I'm calling this with file_get_contents() then trying to decode but I'm getting nothing back at all.
$test = file_get_contents('test.json');
$json = json_decode($test);
echo "<pre>";
print_r($json);
echo "</pre>";
returns:
<pre></pre>
Any ideas why json_decode() is failing to decode?
It is because of a stray comma. You should check for errors:
if (json_last_error() != JSON_ERROR_NONE) {
die(json_last_error_msg());
}
If you have PHP <5.5.0 then you can use this compatibility function:
if ( ! function_exists('json_last_error_msg')) {
function json_last_error_msg() {
static $errors = array(
JSON_ERROR_NONE => null,
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);
$error = json_last_error();
return array_key_exists($error, $errors) ? $errors[$error] : "Unknown error ({$error})";
}
}
Actually it wasn't stray commas as the answerers suggested, JSONLint reported BOM artifacts from UTF-8, I'm assuming from copying and pasting.
Once I ran it through and removed the BOM artifacts it decoded properly.
Thanks to all for your help and suggestions.