I my Laravel app i am using php curl for mailchimp to store and get products data is storing but when i want to fetch data using foreach loop it is showing an error Trying to get property 'stores' of non-object how can i solve this thanks in advance
this is the result when i use dd()
this is the request
public function get_store()
{
$id = "store_1159";
$url = "https://us7.api.mailchimp.com/3.0/ecommerce/stores";
$data = callAPI('GET', $url, false);
$stores = json_decode($data);
//dd($stores );
$result = array();
foreach ($stores as $store) {
echo $store->id;
}
}
this is php curl main function
function callAPI($method, $url, $data=null)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
default:
if($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
$headers = array(
"--user: credentials",
"Authorization: Basic 1232132131",
"Content-Type: application/json",
"Postman-Token: 163f7134-68ca-45bb-9420-ebf2bef7f447",
"cache-control: no-cache"
);
curl_setopt_array($curl,
[
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADER => false,
CURLOPT_URL => $url.'?apikey=12313123'
]);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
try this,
$data = callAPI('GET', $url, false);
$data = json_decode($data);
foreach ($data->stores as $store)
{
echo $store->id;
}
Related
All my efforts failed! I can't POST data to HTTPS Even by using CURL, fopen and file_get_contents!
I always getting a 404 error!
However, when I leech the page using GET method it open with no errors!
But when I using POST method for that page with its same URL it always fail with a 404 error!
My PHP code :
<?php
###########################################
function curl_fopen_getContents( $functionName='curl', $method='GET' )
{
$post_data = http_build_query(array( 'a' => '1' ));
$cookies = 'a=1';
$opts = array('http' => array(
'method' => strtoupper($method),
'header' =>
"Content-type: application/x-www-form-urlencoded\r\n"
."Content-Length: " . strlen($post_data)."\r\n"
."Cookie: $cookies\r\n",
'content' => $post_data,
'timeout' => 60
));
$context = stream_context_create($opts);
///////////////////////////////////
// you can decode it
$https_url = 'my_url_here';
if( $functionName=='fopen' )
{
$result = fopen($https_url, 'r', false, $context); #fpassthru($result); #fclose($result);
}
elseif( $functionName=='file_get_contents' )
{
$result = file_get_contents($https_url, false, $context);
}else{
$result = curl_post($https_url, $method, $post_data, $cookies);
}
return $result;
}
###########################################
function curl_post( $https_url, $method='GET', $post_data='', $cookies='' )
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$https_url);
curl_setopt($ch, CURLOPT_COOKIE, $cookies);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
#curl_setopt($ch, CURLOPT_HEADER, 1);
if( strtoupper($method) !='GET' )
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
$data = curl_exec($ch); if(!$data){ $data=curl_error($ch); }
curl_close($ch);
return $data;
}
###########################################
/*
curl_fopen_getContents( $functionName, $method );
$functionName = curl/fopen/file_get_contents
$method = GET/POST
*/
echo curl_fopen_getContents( 'curl', 'GET' );
###########################################
?>
Can you help please? Thanks Alot.
The problem was that I forget to pass some cookies..
I have used postman to execute curl request and get response from the api. Everything is working perfectly. But as soon as I try to execute same curl within a php while loop. It doesn't works at all.
Searched over the internet but did not found any useful information. I would like to know if there is any other way, other than using curl. I also tried sleep(3) function from php which sleeps loop for 3 seconds but it didn't helped.
Bottom line curl is not working in php loop whereas it works independently.
Below is my code for reference
while (($company = fgets($handle)) !== false) {
// process the line read.
$company = trim($company);
if(!empty($company)) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.domain.com/services/v3/api/entities?search-term=$company&page-size=10000",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer 78654356gvgfdr43wsdxcfg",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response_array = json_decode($response, TRUE);
$items = $response_array['items'];
if (!empty($items)) {
foreach ($items AS $item) {
$tt_id = $item['tt_id'];
$tt_Name = $item['tt_Name'];
$tt_TypeID = $item['tt_TypeID']['id'];
//save to db
}
}
}
}
I tried putting curl init and other setopt before the while loop, but it is not working either.
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_POSTFIELDS, "");
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer 78654356gvgfdr43wsdxcfg",
"cache-control: no-cache"
));
while (($company = fgets($handle)) !== false) {
// process the line read.
$company = trim($company);
if(!empty($company)) {
curl_setopt($curl, CURLOPT_URL, https://api.domain.com/services/v3/api/entities?search-term=$company&page-size=10000);
$response = curl_exec($curl);
$err = curl_error($curl);
$response_array = json_decode($response, TRUE);
$items = $response_array['items'];
if (!empty($items)) {
foreach ($items AS $item) {
$tt_id = $item['tt_id'];
$tt_Name = $item['tt_Name'];
$tt_TypeID = $item['tt_TypeID']['id'];
//save to db
}
}
}
}
curl_close($curl);
So i'm working with the LinkedIn API and i'm trying to share something to my wall but i'm getting the following error:
Couldn't parse share document: error: Unexpected end of file after null
I think something is going wrong with with adding the HTTPHEADERS:
Content-Type: application/json
x-li-format: json
So this is what i'm trying to do:
$parameters = array("comment" => "Check out developer.linkedin.com, I'm currently testing it myself!",
"content" => array( "title" => "LinkedIn Developers Resources",
"description" => "Leverage LinkedIn's APIs to maximize engagement",
"submitted-url" => "https://developer.linkedin.com",
"ubmitted-image-url" => "https://example.com/logo.png"
),
"visibility" => array("visibility" => "anyone")
);
$result = $connection->post("people/~/shares", $parameters);
var_dump($result);
var_dump($result); shows the error message above.
And these are the functions i'm using:
public function post($path, $parameters = []){
$url = $this->createUrl($path);
$parameters = json_encode($parameters);
return $this->curlRequest('POST', $url, $parameters);
}
this is the post function, wich is using the following functions:
private function createUrl($path) {
return self::API_HOST . "/v" . self::API_VERSION . "/" . $path . "?" . self::FORMAT;
}
private function curlRequest($method, $url, $postData = NULL, $accessToken = false){
$curl = curl_init();
switch($method) {
case 'GET':
break;
case 'POST':
curl_setopt($curl, CURLOPT_POST, true);
if($accessToken) {
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData));
} else {
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'x-li-format: json'));
break;
}
if ($accessToken) {
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
} else {
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $this->accessToken));
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $url);
$result = curl_exec($curl);
curl_close($curl);
return json_decode($result, true);
}
Hope someone can help me with this problem.
I typically send an array of strings using CURL in PHP, something like this:
$data = array(
"key1" => $value,
"key2" => $value,
"key3" => $value,
"key4" => $value
);
Then, among other curl_setop settings, post using:
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
This all works fine. But now in addition to those strings, I have 1 dataset that is JSON encoded and I want to post it at the same time. JSON looks like this:
Array ( [ad_info] => {"MoPubAdUnitInteractions":"a","MoPubAdUnitConversations":"b","MoPubAdUnitGroups":"c"} )
I think I figured out how to do it by setting a header saying I'm going to be passing in JSON like this:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
But then, can I simply add another line for the post, but in this case the JSON encoded value like this:
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
I'm kinda shooting in the dark, any suggestions on how I should be thinking about this?
Ok, here is the full example:
From Processing The Form Post:
$community_id = $_POST["communityid"];
$community_name = $_POST["communityname"];
$community_apns_name = $_POST["communityapnsname"];
$community_download_url = $_POST["communitydownloadurl"];
$community_open_tagging = $_POST["communityopentagging"];
$community_pull_content = $_POST["communitypullcontent"];
$community_push_content = $_POST["communitypushcontent"];
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
);
$json_data = array("ad_info" => $community_ad_info);
$api_querystring = $gl_app_api_url . "communities";
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null, $json_data);
And the Function in PHP I'm calling to do the CURL:
function CallAPI($method, $url, $data = false, $device_id = false, $community_id = false, $json_data = false) {
if (!$community_id) { // IF NO COMMUNITY ID IS PROVIDED
global $gl_community_id;
$community_id = $gl_community_id;
}
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "XXXX:XXXXX");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Disable the SSL verificaiton process
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if ($device_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("device_id:" . $device_id));
if ($community_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Afty-Community:" . $community_id));
if ($json_data)
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);
// Confirm cURL gave a result, if not, write the error
$response = curl_exec($curl);
if ($response === FALSE) {
die("Curl Failed: " . curl_error($curl));
} else {
return $response;
}
}
Any help is greatly appreciated.
You use wrong approach. Setting CURLOPT_POSTFIELDS option twice doesn't lead to result you expected since each setting call discards effect of previous one.
Instead of this, you have to append extra data ($community_ad_info) to the main POST data ($data) before passing it to CURLOPT_POSTFIELDS option.
...
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
"ad_info" => $community_ad_info
);
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null);
...
This is untested of course but it should do what you need.
function CallAPI($method, $url, $data = false, $device_id = false, $community_id = false, $json_data = false) {
if (!$community_id) { // IF NO COMMUNITY ID IS PROVIDED
global $gl_community_id;
$community_id = $gl_community_id;
}
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PATCH":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "XXXX:XXXXX");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Disable the SSL verificaiton process
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if ($device_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("device_id:" . $device_id));
if ($community_id)
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-Afty-Community:" . $community_id));
// Confirm cURL gave a result, if not, write the error
$response = curl_exec($curl);
if ($response === FALSE) {
die("Curl Failed: " . curl_error($curl));
} else {
return $response;
}
}
And now the actualy logic
$community_id = $_POST["communityid"];
$community_name = $_POST["communityname"];
$community_apns_name = $_POST["communityapnsname"];
$community_download_url = $_POST["communitydownloadurl"];
$community_open_tagging = $_POST["communityopentagging"];
$community_pull_content = $_POST["communitypullcontent"];
$community_push_content = $_POST["communitypushcontent"];
$community_ad_info = json_encode($_POST["ad_info"]);
$data = array(
"name" => $community_name,
"apns_name" => $community_apns_name,
"download_url" => $community_download_url,
"open_tagging" => $community_open_tagging,
"pull_content" => $community_pull_content,
"push_content" => $community_push_content,
"ad_info" => $community_ad_info
);
$api_querystring = $gl_app_api_url . "communities";
$response = CallAPI('PATCH', $api_querystring, $data, $device_id = null, $community_id = null);
The things to note here are,
the new content tyoe header tells it to be processed as a form post.
removal of the $json_data array, the "ad_info" key is not just added into the $data array
When you process this on the other side you can access the ad_info like this
$ad_info = json_decode($_POST['ad_info']);
You can access the other fields with
$apns_name = $_POST['apns_name'];
I am using Codeigniter and Phil's REStful API.
I am making a call to the server and the problem is it return a NULL value. The value that should be return is a blob that is 65000 in length. I reckon its because of the length of the blob, but I don't know how to solve this issue.
Here's how i call the api:
$resp = call('upload_api/upload/format/json/', array('uploaded_files' => $_FILES['upload'], 'file_details' => 'test'));
echo '<pre>'; print_r($resp);
public static function call($resource, $params, $method='get')
{
if (empty($params))
{
$params = array();
}
$headers = '';
$url = self::API_URL . $resource;
$curlObj = curl_init();
curl_setopt_array($curlObj,
array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 20
));
switch ($method)
{
case 'get':
$query_str = http_build_query($params);
$url = $url .= '?' . $query_str;
curl_setopt($curlObj, CURLOPT_URL, $url);
break;
case 'put':
$headers[] = 'Content-Type: application/json';
curl_setopt($curlObj, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlObj, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curlObj, CURLOPT_POSTFIELDS, json_encode($params));
break;
case 'post':
$headers[] = 'Content-Type: application/json';
curl_setopt($curlObj, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlObj, CURLOPT_POST, true);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, json_encode($params));
break;
default:
// error message
}
$data = curl_exec($curlObj);
$contentType = curl_getinfo($curlObj, CURLINFO_CONTENT_TYPE);
switch ($contentType)
{
case 'application/json':
$data = json_decode($data, true);
break;
}
curl_close($curlObj);
return $data;
}
Here's the method:
require APPPATH.'/libraries/REST_Controller.php';
class Upload_api extends REST_Controller {
public function upload_get()
{
$this->load->model('Upload_File');
$upload_file = new Upload_File();
$total_rows = $upload_file->count();
$upload_file->get(1, 0)->all;
// file_content is a blob
$this->response(array('file' => $upload_file->file_content, 'total_rows' => $total_rows), 200);
}
}
I'm not fully sure of the solution, but I do this when trying to solve REST bugs with the libary:
You can output:
$this->response($_SERVER);
and
$this->response($_POST);
etc. to see all the server variables, so you can check the length of the response and the headers.