I am new to JSON and having a problem with checking at getting the error message when there is an error. My code works fine when the result is not an error, so I do somewhat understand what I am doing.
This is the error JSON that I am trying to parse:
{
"error": {
"message": "Unsupported get request.",
"type": "GraphMethodException",
"code": 100
}
}
Here is my code that fails:
$jsonurl = "http://graph.facebook.com/JubilationDanceMinistry";
//valid $jsonurl = "http://graph.facebook.com/WhitworthACM";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
var_dump($json_output);
// This returns NULL
if (property_exists($json_output->error)) {
echo "<p>error: $json_output->error->{'message'} </p>";
} else {
echo "<p>no error :(</p>";
}
$facebook_id = $json_output->{'id'};
$facebook_name = $json_output->{'name'};
$facebook_link = $json_output->{'link'};
Because the url returns the 400 Bad Request.
By default, you can't use file_get_contents function to get the response content when the http status code is 400.
You need to set ignore_errors options to true.
$opts = array(
'http'=>array(
'ignore_errors' => true
)
);
$context = stream_context_create($opts);
$jsonurl = "http://graph.facebook.com/JubilationDanceMinistry";
$json = file_get_contents($jsonurl, false, $context);
var_dump($json);
You can't chain multiple ->'s with string interpolation.
You'll have resort to passing multiple arguments to echo or to string concatenation:
echo "<p>error: ", $json_output->error->{'message'}, " </p>";
Related
Why can't I echo $phone_number in this code? It says
Undefined index: phone_number. but when I echo $response it returns the values
<?php
$ch = curl_init( 'https://mighty-inlet-78383.herokuapp.com/api/hotels/imagedata');
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => TRUE
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
echo 'No responce';
}
// Decode the response
$responseData = json_decode($response);
// Print the date from the response
$phone_number = $responseData['phone_number'];
echo $phone_number;
?>
Because these are arrays within arrays you need to go one level deeper to get the data you want. First, make sure you're returning the JSON as an array, using the 'true' attribute:
$responseData = json_decode($response, true);
Then you can get the first phone number (or any phone number by changing the array index):
echo $responseData[0]['phone_number'];
echo $responseData[1]['phone_number'];
You can also loop through the responses:
foreach($responseData AS $response) {
echo $response['phone_number'];
}
I am trying to read JSON values using the "Have I Been PWNED" API v2.
I have tried two different ways to display the data using the URL (https://haveibeenpwned.com/api/v2/breach/Adobe) and using a local .json file, but both methods display nothing.
Method 1 (URL):
index.php
<?php
// Breach Title
$breach_title = 'Adobe';
// JSON URL
$url = 'https://haveibeenpwned.com/api/v2/breach/'.$breach_title;
// Put the contents of the url into a variable
$json = file_get_contents($url);
// Decode the JSON feed
$object = json_decode($json);
// Echo Results
echo $object[0]->Title;
echo $object[0]->Name;
echo $object[0]->Domain;
echo $object[0]->Description;
echo $object[0]->BreachDate;
?>
Method 2 (Local .json file):
index.php
<?php
// Put the contents of the file into a variable
$json = file_get_contents("Adobe.json");
// Decode the JSON feed
$object = json_decode($json);
// Echo Results
echo $object[0]->Title;
echo $object[0]->Name;
echo $object[0]->Domain;
echo $object[0]->Description;
echo $object[0]->BreachDate;
?>
Adobe.json
{
"Title": "Adobe",
"Name": "Adobe",
"Domain": "adobe.com",
"BreachDate": "2013-10-04",
"AddedDate": "2013-12-04T00:00:00Z",
"ModifiedDate": "2013-12-04T00:00:00Z",
"PwnCount": 152445165,
"Description": "In October 2013, 153 million Adobe accounts were breached with each containing an internal ID, username, email, <em>encrypted</em> password and a password hint in plain text. The password cryptography was poorly done and many were quickly resolved back to plain text. The unencrypted hints also disclosed much about the passwords adding further to the risk that hundreds of millions of Adobe customers already faced.",
"DataClasses": [
"Email addresses",
"Password hints",
"Passwords",
"Usernames"
],
"IsVerified": true,
"IsFabricated": false,
"IsSensitive": false,
"IsActive": true,
"IsRetired": false,
"IsSpamList": false,
"LogoType": "svg"
}
I have been using the following as resources:
Read JSON values from URL via PHP
How do I extract data from JSON with PHP?
https://stackoverflow.com/a/29308899/9925901
Also no output using this in both methods:
print_r($object);
With the version of Adobe.json in your question, you don't need the [0] to access the data...
$object = json_decode($json);
// Echo Results
echo $object->Title;
echo $object->Name;
echo $object->Domain;
echo $object->Description;
echo $object->BreachDate;
To get the file URL with https, it may be easier to use CURL...
// Breach Title
$breach_title = 'Adobe';
// JSON URL
$url = 'https://haveibeenpwned.com/api/v2/breach/'.$breach_title;
// Put the contents of the url into a variable
//$json = file_get_contents($url);
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false // Disabled SSL Cert checks
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$json = curl_exec( $ch );
// Decode the JSON feed
$object = json_decode($json);
$object = json_decode($json);
// Echo Results
echo $object->Title;
echo $object->Name;
echo $object->Domain;
echo $object->Description;
echo $object->BreachDate;
Here is my corrected code after reading the HIBP APIv2 closer thanks to #MonkeyZeus
Just needed to add a user agent and removed [0].
<?php
ini_set('user_agent', 'Test App');
// Breach Title
$breach_title = 'Adobe';
// JSON URL
$url = 'https://haveibeenpwned.com/api/v2/breach/'.$breach_title;
// Put the contents of the url into a variable
$json = file_get_contents($url);
// Decode the JSON feed
$object = json_decode($json);
// Echo Results
echo $object->Title;
echo $object->Name;
echo $object->Domain;
echo $object->Description;
echo $object->BreachDate;
?>
true json url
$url = 'https://tr.api.pvp.net/api/lol/tr/v1.4/summoner/by-name/r2aper1tuar?api_key=RGAPI-2F65B634-F9C5-4DA7-A5E3-1D955D5D1E3B';
$content = file_get_contents($url);
$json = json_decode($content);
These codes work but if JSON url is not true. It will show error on index.php
How can i check these error.
not true json
if i use "not true JSON" , I take this error.
{
"status": {
"message": "Not Found",
"status_code": 404
}
}
Now how to check errors ?
Check the response:
if( property_exists ( $json , "status" ) )
{
$status_code = $json -> status -> status_code;
$message = $json -> status -> message;
// do something...
}
I'm trying to understand how to record the result of a curl GET request using php. I'm looking at outputing part or all of the result to mysql.
https://github.com/cloudtrax/docs/blob/master/api/code/php/simple_api_server_test_harness.php
function invoke_curl($method, $endpoint, $headers, $json) {
$api_server = 'https://api.cloudtrax.com';
try {
// get a curl handle then go to town on it
$ch = curl_init($api_server . $endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if ($result == FALSE) {
if (curl_errno($ch) == 0)
echo "#### NOTE ####: nil HTTP return: This API call appears to be broken" . "\n";
else
throw new Exception(curl_error($ch), curl_errno($ch));
}
else
echo "RESULT: \n" . $result . "\n";
}
The $result shows like this:
{
"clients": {
"ssid2": 4,
"ssid1": 10
},
"rows": [
{
"time": "2016-03-23T02:45:00Z",
"ssid2": {
"traffic": {
"unclassified": {
// etc...
How can I associate each part of the result too a variable so I can then input too mysql?
It looks like this result in json format. You can use json_decode to decode it:
$resultObject = json_decode($result);
$clients = $resultObject->clients;
// ... get other data from result
The code below will convert the json into a PHP array. You can then use the indexes of the array to pull out values.
$result = json_decode($result);
$clients = $result->clients;
// Some MySQL queries
If your response is a JSON response then you can simply use php's json_decode to get parsed object.
$result = curl_exec($ch);
//to get associative array passing true
$jsonObj = json_decode($result, true);
$clients = $jsonObj['clients'];
$rows = $jsonObj['rows'];
You can refer to these answers for more detail:
Parsing JSON object in PHP using json_decode and
Parsing JSON file with PHP
I'm struggling with parsing a web service response JSON in cases where the service returns an error.
Example JSON - success flow:
{
"Response": [{
"iconPath" : "/img/theme/destiny/icons/icon_psn.png",
"membershipType": 2,
"membershipId": "4611686018429261138",
"displayName": "Spuff_Monkey"
}],
"ErrorCode": 1,
"ThrottleSeconds": 0,
"ErrorStatus": "Success",
"Message": "Ok",
"MessageData":{}
}
Example JSON - error flow:
{
"ErrorCode": 7,
"ThrottleSeconds": 0,
"ErrorStatus": "ParameterParseFailure",
"Message": "Unable to parse your parameters. Please correct them, and try again.",
"MessageData": {}
}
Now my PHP:
function hitWebservice($endpoint) {
$curl = curl_init($endpoint);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
$json_response = curl_exec($curl);
if(curl_exec($curl) === false) {
echo "Curl error: " . curl_error($curl);
}
curl_close($curl);
$array_response = json_decode($json_response, true);
$function_response = array();
if (!isset($array_response['Response'])) {
$function_response = $array_response;
} else {
$function_response = $array_response['Response'];
}
return $function_response;
}
What I'm trying to achieve is when the JSON includes the "Response" block I put that in a new array and return only that detail from the function, where "Response" isn't present I want to return the full JSON as an array.
However at present, where there is no "Response" I get an empty array.
There's something wrong with my logic and I can't get past it in my tiny mind, so it's time to reach out for help!
Judging from the fact that Response is an array of objects in the JSON, I suspect that the error-flow response may also contain a Response-field, but with an empty array as value ([]). That would explain your current result.
Therefore, do not check for the existence of Response. It may just be an empty array. Instead, check for the ErrorCode, ErrorStatus or ErrorMessage (whichever you think is most suitable). For example:
if ($array_response['ErrorStatus'] != "Success") {
$function_response = $array_response;
} else {
if (!isset($array_response['Response'])) {
$function_response = null;
} else {
$function_response = $array_response['Response'];
}
}
In the Success-case, you want to check for existence of Response, so that if it does not exist (but it is expected), you can raise some error).
Another possible solution is to count the number of responses:
if (!isset($array_response['Response'])) {
$function_response = $array_response;
} else {
if (count($array_response['Response']) > 0) {
$function_response = $array_response['Response'];
} else {
$function_response = $array_response;
}
}
If you notice, both a good and a bad response contain an ErrorCode
You would be better designing your code to work from this field rather than test a field that may or may not exist.
So try this instead :-
$array_response = json_decode($json_response, true);
switch ( $array_response['ErrorCode'] ) {
case 1 :
do_errorCode_1_processing($array_response)
break;
case 2 :
do_errorCode_2_processing($array_response)
break;
// etc etc
}
isset () is not the right function for checking if the key in an array is present or not.
Use array_key_exists () instead.
http://php.net/manual/en/function.array-key-exists.php
so your code should look like this:
$array_response = json_decode($json_response, true);
$function_response = array();
if (array_key_exists('Response', $array_response)) {
$function_response = $array_response['Response'];
} else {
$function_response = $array_response;
}
return $function_response;
The above should do the trick.