Trouble With API Curl Response(php) - php

I am having trouble with the response from Companies House API. I am making the following curl request from a php page:
$request_url_1 ='https://api.companieshouse.gov.uk/company/' ;
$company_number = 11495745;
$request_url_2 = '/officers';
$request_url = $request_url_1 . $company_number . $request_url_2;
$ch = curl_init($request_url);
$headers = array(
'Content-Type: application/json',
'Authorization: Basic '. base64_encode("$chkey:")
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$content = curl_exec($ch);
curl_close( $ch );
$contents = json_decode($content,true);
The following is the response that is 'pasted' on the php page after sending the curl request, and I cannot seem to get at the contents/value of the $contents variable that should contain the curl response.
{
"active_count":1,
"items_per_page":35,
"kind":"officer-list",
"etag":"6cc48213158205c9fa85492a4c2ef0a98b56b2f1",
"resigned_count":2,
"items":[
{
"date_of_birth":{
"year":1963,
"month":2
},
"appointed_on":"2019-08-01",
"nationality":"British",
"address":{
"address_line_1":"Moorside Crescent",
"country":"United Kingdom",
"address_line_2":"Sinfin",
"postal_code":"DE24 9PH",
"locality":"Derby",
"premises":"75"
},
"occupation":"Company Director",
"links":{
"officer":{
"appointments":"/officers/IryiaaBZodlGNaOP0Rf3Pb2GnO8/appointments"
}
},
"name":"MILLER, Eira",
"country_of_residence":"England",
"officer_role":"director"
},
{
"date_of_birth":{
"month":3,
"year":1987
},
"nationality":"English",
"occupation":"Company Director",
"address":{
"locality":"Derby",
"address_line_1":"Moorside Crescent",
"premises":"75",
"country":"United Kingdom",
"postal_code":"DE24 9PH",
"address_line_2":"Sinfin"
},
"appointed_on":"2018-12-10",
"resigned_on":"2019-07-31",
"name":"KING, Kimberley Rachel",
"links":{
"officer":{
"appointments":"/officers/av7G3-iF_9-FXhRH2xm-IxejeGQ/appointments"
}
},
"country_of_residence":"United Kingdom",
"officer_role":"director"
},
{
"address":{
"postal_code":"DE24 9PH",
"locality":"Derby",
"country":"United Kingdom",
"premises":"75",
"address_line_2":"Sinfin",
"address_line_1":"Moorside Crescent"
},
"occupation":"Managing Director",
"nationality":"British",
"appointed_on":"2018-08-01",
"resigned_on":"2018-12-10",
"officer_role":"director",
"country_of_residence":"United Kingdom",
"links":{
"officer":{
"appointments":"/officers/X9nlVD6qIIENMjaH946__4CB3QE/appointments"
}
},
"name":"MARTIN, Katey",
"date_of_birth":{
"month":6,
"year":1968
}
}
],
"links":{
"self":"/company/11495745/officers"
},
"inactive_count":0,
"start_index":0,
"total_results":3
}
I have tried returning result as non-associative array and access it through normal array but no joy there either.
FluffyKitten kindly supplied the following code to perform the extraction of the name field:
$item = $contents["items"];
foreach($item as $items){
echo $items["name"];
}
However, this couldn't access the required data. A print_r of $contents results in '1' and a var_dump (1)

There are a couple of problem with your code:
You are mixing up code for accessing arrays and objects
You are looping when there is no need for loops
You are using json_decode($content,true), and by passing in that true parameter, you are converting the result into associative arrays, but then you try to access items as the property of an object.
Because you have converted the contents to an associative array, you can easily access the information you want using the correct keys, e.g.:
$item = $contents["items"];
foreach($item as $items){
echo "<p>".$items["name"];
}
Reference PHP json_decode Documentation
UPDATE:
Your question has changed totally - it was about how to loop through the variable with the results, but now it seems that the problem is saving the results as a variable in the first place.
You need to set the CURLOPT_RETURNTRANSFER option to true so that the result is not output directly (I assume this is what you mean by the result being "pasted" into the PHP page).
Add this to your CURL code, and if the rest of your code is correct, the result should be saved in the $content variable so you can use it to loop through using the code above:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Related

Unable to fetch single data from JSON Curl Output in PHP [duplicate]

This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How to use cURL to get jSON data and decode the data?
(6 answers)
Closed 10 months ago.
I have a code which should fetch courseID from JSON response obtained , But currently it is not fetching anything . It shows me the entire response and not one . can someone help me with this .
JSON response obtained.
{
"results": [
{
"CourseID": "ASPO",
"Success": "Yes"
}
]
}
i just want to retrieve the CourseID.
and below is my code
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://AbC:3939');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "ABC=AE");
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Authorization: Bearer hjhjhjhjhjhj338sj';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch) ;
}else{
$result_value = json_decode($result);
print_r($result_value->results[0]->CourseID);
}
curl_close($ch);
?>
I have tried this with your shared result and got the COURSEID.
$resp = '{
"results": [
{
"CourseID": "ASPO",
"Success": "Yes"
}
]
}';
$res = json_decode($resp);
print_r($res->results[0]->CourseID);
Note: this answers the original question (extract information from JSON response).
The top level element in your JSON string is an object with a single results key that holds everything. You aren't referencing such key anywhere in your code.
The name of the local PHP variable where you store the results is irrelevant, there isn't any automatic behaviour linked to that.
If you use json_decode() with the $associative flag you get JSON objects converted to PHP arrays (JSON arrays become PHP arrays no matter the flags). If unsure, just inspect your data with either a step debugger or e.g. var_dump($result_value):
array(1) {
'results' =>
array(1) {
[0] =>
array(2) {
'CourseID' =>
string(4) "ASPO"
'Success' =>
string(3) "Yes"
}
}
}
In php you can access array elements by specifying the key inside square brackets so:
var_dump($result_value['results'][0]['CourseID'], $result_value['results'][0]['Success']);
string(4) "ASPO"
string(3) "Yes"

Extract data from JSON with PHP?

i want to take data of username(david) from this Json , I saw the similar question i try more than 100 times but i can not , I need exact answer if it's possible.
thanks in advance
{
"related_assets": [],
"orders": [],
"auctions": [],
"supports_wyvern": true,
"top_ownerships": [
{
"owner": {
"user": {
"username": "david"
},
"",
"address": "",
"config": ""
},
"quantity": "1"
}
],
"ownership": null,
"highest_buyer_commitment": null
}
and i coded as below :
<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
//the second parameter turns the objects into an array
$decodedData = json_encode($response, true);
$owner = $decodedData['top_ownerships'][0]['owner'];
$username = $owner['user']['username'];
echo $username;
}
the output is "
please help thanks
your code is completely current! and it works like charm!
but you made a very ambiguous mistake in your JSON code
you're using this ” instead of " (double quotes) there "david” <----
they exactly look the same!
and also you missed {} in the beginning and end of your JSON code
checkout your json code here it's the best tool for this
<?php
$code = '{
"top_ownerships": [{
"owner": {
"user": {
"username": "david"
},
"profile_img_url": "",
"address": "",
"config": ""
},
"quantity": "1"
}]
}';
$decodedData = json_decode($code, true);
$owner = $decodedData['top_ownerships'][0]['owner'];
$username = $owner['user']['username'];
echo $username;
?>
To start with, it's important you understand how to access json fields and key php;
Assuming the above values are stored in a file known as data.json, we can extract the values like this:
$data = file_get_contents('data.json');
//the second parameter turns the objects into an array
$decodedData = json_decode($data, true);
$owner = $decodedData['top_ownerships'][0]['owner'];
$username = $owner['user']['username'];
//echo $username
The above would work if your json file or data is properly encoded.
first you have to store your JSON into a variable, lets call it $json.
$jsonArray = json_decode($json,true);
And set your key name, the key you want from your JSON.
$key = "owner";
$owner= $jsonArray[$key];
You also can read like an object:
$owner= $jsonObj->$key;
Try
$object = json_decode('{"owner": {"user": {"username": "david”},"profile_img_url": "","address": "","config": ""},"quantity": "1"}')
echo $object->owner->user->username
This will make the JSON an object that you can access by using the -> accessor

Facebook Messenger Chatbot - I can't answer to a postback

I'm writing a bot for Facebook in PHP. I'm able to send text and send and answer to quickreplies. However is impossible to me to answer to a postback. I use ngrok for localhost testing purposes but I know that it's not that the problem since 1. it doesn't work on my vps neither 2. All the other functionalities work as expected.
My code for sending the post-back :
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"What do you want to do next?",
"buttons":[
{
"type":"postback",
"title":"Start Chatting",
"payload":"USER_DEFINED_PAYLOAD"
}
]
}
}
}
}';
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;
$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
if(!empty($message_body['message'])){
$result = curl_exec($ch);
}
Then, when I receive the post-back I get this from FB messenger :
{
"object": "page",
"entry": [
{
"id": "590445400970275",
"time": 1494251031827,
"messaging": [
{
"recipient": {
"id": "590445400970275"
},
"timestamp": 1494251031827,
"sender": {
"id": "1075794782546272"
},
"postback": {
"payload": "USER_DEFINED_PAYLOAD"
}
}
]
}
]
}
and my code to parse it :
$input = json_decode(file_get_contents('php://input'), true);
$message_body = $input['entry'][0]['messaging'][0];
$sender = $message_body['sender']['id'];
if (isset($message_body['postback'])){
//Reception d'un postback
$postback = $message_body['postback']['payload'];
if ($postback == "USER_DEFINED_PAYLOAD"){
// The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"messagetoreply"
}
}';
}
}
This is sent by the curl function as the message before.
However the messenger never receives an answer :
Could anyone help me finding out where's the problem ?
Thank you very much
There was a mistake in my code at this part :
if(!empty($message_body['message'])){
$result = curl_exec($ch);
}
since the $message_body var is not 'message' but a 'postback', the curl was not sending the response.

Illegal string offset 'name', code worked with example json response

I'm currently working on a website to control my SmartBulbs at home via a webpage. To do so I use the provided API.
I tried my code with an example json response from the manufacturers website. Everything worked fine and all the lights listed in the example response where represented by divs with the names of the lights.
When I tried my code at home (called the API like in the code) I got a valid response but I also got an error which stated Illegal string offset 'label'. What am I doing wrong?
Everything worked fine when I used the example response. The response when I use the API looks the same for me. Shouldn't it also work then?
You can find everything down below. If you need some mor information just ask :)
php code
function get_lights(){
$link = "https://api.lifx.com/v1/lights/all";
$authToken = "I inserted my token here and got a valid response";
$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $headers);
$response = curl_exec($ch);
$json = json_decode($response, true);
$html = null;
foreach($json as $object)
{
$html.= '<div class="element" onclick="get_info();">' . $object['label'] . '</div>';
}
return $html;
}
example response
[
{
"id": "d3b2f2d97452",
"uuid": "8fa5f072-af97-44ed-ae54-e70fd7bd9d20",
"label": "Left Lamp",
"connected": true,
"power": "on",
"color": {
"hue": 250.0,
"saturation": 0.5,
"kelvin": 3500
},
"infrared": "1.0",
"brightness": 0.5,
"group": {
"id": "1c8de82b81f445e7cfaafae49b259c71",
"name": "Lounge"
},
"location": {
"id": "1d6fe8ef0fde4c6d77b0012dc736662c",
"name": "Home"
},
"last_seen": "2015-03-02T08:53:02.867+00:00",
"seconds_since_seen": 0.002869418,
"product": {
"name": "LIFX+ A19",
"company": "LIFX",
"identifier": "lifx_plus_a19",
"capabilities": {
"has_color": true,
"has_variable_color_temp": true,
"has_ir": true,
"has_multizone": false
}
}
}
]
my API response
[
{
"id":"d073d513bfd6",
"uuid":"02ea5835-9dc2-4323-84f3-3b825419008d",
"label":"MainLight",
"connected":true,
"power":"on",
"color":{
"hue":27.581597619592586,
"saturation":0.0,
"kelvin":2500
},
"zones":null,
"brightness":0.49999237048905165,
"group":{
"id":"d5aa0e1180293e0af56607cbe47f4940",
"name":"MyRoom"
},
"location":{
"id":"451e4b376a38062cdd10c54ab2698975",
"name":"My Home"
},
"product":{
"name":"Color 1000",
"identifier":"lifx_color_a19",
"company":"LIFX",
"capabilities":{
"has_color":true,
"has_variable_color_temp":true,
"has_ir":false,
"has_multizone":false
}
},
"infrared":null,
"last_seen":"2017-02-18T21:40:58.164+00:00",
"seconds_since_seen":0.001675218
}
]
You're setting the wrong option for your cURL handle:
$ch = curl_init($link);
$headers = array('Authorization: Bearer ' . $authToken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

Pulling data from weird JSON array response

I am working with an API and the response comes back weird. I need to grab the ID field from the response below.
{
"message_campaigns": [
{
"embedded_errors": [],
"id": "2729",
"is_legacy_message": false,
"is_setup_complete": false,
"message_campaign_type_id": 1,
"name": "Message Campaign 1",
"organization_id": 123
}
]
}
Below is my attempt:
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
$responseData = json_decode($result, TRUE);
print_r($responseData);
I have tried several methods and cannot get it to work
$responseData[0]['id'];
$responseData->id;
I can't figure out how to get the id to display.
Assuming your curl_exec actually returns a response because you've set curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
If I look at your json response you need:
$responseData['message_campaigns'][0]['id'];
It's because the result is an array, as you pass the second parameter as true to json_decode:
When TRUE, returned objects will be converted into associative arrays.
In JSON, {} stands for objects, and [] stands for array. You've converted all objects to associative arrays, so this'll work:
$responseData['message_campaigns'][0]['id']
You have the second parameter of json_decode set to true, so an array (not an object) will be returned.
You'll also need to access message_campaigns as the first item in the array.
$responseData['message_campaigns'][0]['id'];
This can be tested:
$result = <<< EOT
{
"message_campaigns": [
{
"embedded_errors": [],
"id": "2729",
"is_legacy_message": false,
"is_setup_complete": false,
"message_campaign_type_id": 1,
"name": "Message Campaign 1",
"organization_id": 123
}
]
}
EOT;
$responseData = json_decode($result, TRUE);
echo $responseData['message_campaigns'][0]['id'];
// 2729

Categories