PHP API With JSON - php

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";
?>

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;

Getting data from json and passing to url

Want to send the json data to my url, when the json is received i receive all the json data on the url and not the data from 'resolvedQuery'
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true);
$results = $update['result']['resolvedQuery'];
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data" . urlencode(json_encode($update));
Json Data
{
"id": "4ed272a3-b9a4-4f18-a67e-10e12e4f4149",
"timestamp": "2017-12-10T10:07:54.282Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "turn livingroom light on",
"action": "",
"actionIncomplete": false,
"parameters": {
"power-toggle": "on",
"room": "livingroom"
},
"contexts": [],
"metadata": {
"intentId": "19764ecc-715c-4b25-960f-9845f2aef1f9",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 503,
"intentName": "lights"
},
"fulfillment": {
"speech": "Ok, Turning livingroom light on",
"messages": [
{
"type": 0,
"speech": "Ok, Turning livingroom light on"
}
]
},
"score": 1
},
"status": {
"code": 206,
"errorType": "partial_content",
"errorDetails": "Webhook call failed. Error: Webhook response was empty.",
"webhookTimedOut": false
},
"sessionId": "395d3517-05da-42ac-9037-dadac519ab0b"
}
How do i get data from 'resolvedQuery' and send it to my URL
In the code you provided, you have the following line of code
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data"
. urlencode(json_encode($update));
You are appending to the URL parameter message the results of json_decode($update_response, true). $update_response contains all the decoded JSON data posted by the HTTP request which is not what you want.
I believe what you want is a new parameter called resolved-query to be set to the results of json_decode($result, true).
Try chaninging your $url variable to the following:
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data&resolved-query="
. urlencode(json_encode($result));
URL will be set to the following string:
https://autoremotejoaomgcd.appspot.com/sendmessage?
key=APA91bEq&
message=Data&
resolved-query=turn+livingroom+light+on

smsgateway.me store message status in php variable

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!

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

Parsing JSON object in PHP using json_decode

I tried to request the weather from a web service supplying data in JSON format. My PHP request code, which did not succeed was:
$url="http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[0]->weather->weatherIconUrl[0]->value;
This is some of the data that was returned. Some of the details have been truncated for brevity, but object integrity is retained:
{ "data":
{ "current_condition":
[ { "cloudcover": "31",
... } ],
"request":
[ { "query": "Schruns, Austria",
"type": "City" } ],
"weather":
[ { "date": "2010-10-27",
"precipMM": "0.0",
"tempMaxC": "3",
"tempMaxF": "38",
"tempMinC": "-13",
"tempMinF": "9",
"weatherCode": "113",
"weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "N",
"winddirDegree": "356",
"winddirection": "N",
"windspeedKmph": "5",
"windspeedMiles": "3" },
{ "date": "2010-10-28",
... },
... ]
}
}
}
This appears to work:
$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['data']['weather'] as $item) {
print $item['date'];
print ' - ';
print $item['weatherDesc'][0]['value'];
print ' - ';
print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
print '<br>';
}
If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.
If you use the following instead:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
The TRUE returns an array instead of an object.
Try this example
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
http://php.net/manual/en/function.json-decode.php
NB - two negatives makes a positive . :)
Seems like you forgot the ["value"] or ->value:
echo $data[0]->weather->weatherIconUrl[0]->value;
When you json decode , force it to return an array instead of object.
$data = json_decode($json, TRUE); -> // TRUE
This will return an array and you can access the values by giving the keys.
You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.
While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
to make sure you are using the weatherIconUrl for the correct date instance.

Categories