Please help me to decode this below output, which I got when I run cURL.
Here is my code:
$headers = array(
'Accept:application/json',
'X-TB-PARTNER-AUTH: 45504852:abcdksalkrjwejkrjr'
);
$process = curl_init();
curl_setopt($process, CURLOPT_URL,"https://api.opentok.com/session/create");
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, 'p2p.preference=disabled');
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
$server_output = curl_exec($process);
print_r($server_output);
And my output is:
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 14 Mar 2016 10:10:19 GMT
Content-Type: application/json
Connection: keep-alive
Access-Control-Allow-Origin: *
Content-Length: 180
Strict-Transport-Security: max-age=31536000; includeSubdomains
[{"session_id":"2_MX40NTUwNDg1Mn5-MTQ1Nzk1MDIxOTVNGZmUwS1N3bFF2LzhvREZORVN-fg","partner_id":"404852","create_dt":"Mon Mar 12 03:10:19 PDT 2016","media_server_url":""}]
Are you confused by the fact HTTP headers are included in the output?
If so - drop this line: curl_setopt($process, CURLOPT_HEADER, 1);
That is responsible for including the HTTP headers in the output. (See http://php.net/manual/en/function.curl-setopt.php )
Use json_decode function to parse it as an object or array:
$result = '[{"session_id":"2_MX40NTUwNDg1Mn5-MTQ1Nzk1MDIxOTVNGZmUwS1N3bFF2LzhvREZORVN-fg","partner_id":"404852","create_dt":"Mon Mar 12 03:10:19 PDT 2016","media_server_url":""}]';
echo "<pre>";
$json = json_decode($result,true);
print_r($json);// You may access print_r($json{0}->create_dt); etc
References:
json_decode - PHP Manual
Related
I'm using curl with PHP for getting the header response of an API call.
This is my code:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://localapi.com/v1/users');
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("authorization: Basic dmt5MVVTeXg3ZXpKYXVEZGtta2phZThfQ0tXa2tTQkY6"));
$response = curl_exec($curl);
The $response returna the header:
HTTP/1.1 200 OK Date: Wed, 15 Jun 2016 13:48:43 GMT Server:
Apache/2.4.18 (Unix) PHP/5.5.31 X-Powered-By: PHP/5.5.31
X-Rate-Limit-Limit: 1 X-Rate-Limit-Remaining: 0 X-Rate-Limit-Reset: 0
X-Pagination-Total-Count: 1 X-Pagination-Page-Count: 1
X-Pagination-Current-Page: 1 X-Pagination-Per-Page: 20 Link: ;
rel=self Content-Type: application/json; charset=UTF-8 1
Is there a method for access to the single header variables like an array?
Thanks in advance for the help.
You can assign a callback for Curl to process the headers in the response using CURLOPT_HEADERFUNCTION. By providing the $headers variable for the callback to assign the results, you can access them as an array after curl_exec has finished.
$headers = [];
curl_setopt($curl, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$headers) {
$matches = array();
if ( preg_match('/^([^:]+)\s*:\s*([^\x0D\x0A]*)\x0D?\x0A?$/', $header, $matches) )
{
$headers[$matches[1]][] = $matches[2];
}
return strlen($header);
});
curl_exec($curl);
$headers will now contain an associative array of the response headers
How can i get the value of fee in this response
I am integrating the postman api in the php application, for that i am using a curl call from php,
here is the code
<?php
class PostMates extends Controller {
public function getDeliveryQuote()
{
$url = "https://api.postmates.com/v1/customers/cus_XX/delivery_quotes";
$uname = "70538e7";
$pwd = "xxxx";
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded','Accept: application/json'));
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $uname . ":" . $pwd);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, "dropoff_address=20 McAllister St, San Francisco, CA 94102&pickup_address=101 Market St, San Francisco, CA 94105");
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
$return = curl_exec($process);
curl_close($process);
//var_dump($return);
print_r($return);
}
}
While i do print_r and var_dump, below given is the response.
How can i get the fee amount from the resonse.
I tried like $response->fee and $resonse['fee'], but i don't get the result.
How can i get it . Help pls
HTTP/1.1 200 OK
Server: cloudflare-nginx
Date: Sun, 28 Feb 2016 18:26:14 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=d7e72569c2358ea8636fac1a1054815081456683973; expires=Mon, 27-Feb-17 18:26:13 GMT; path=/; domain=.postmates.com; HttpOnly
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
CF-RAY: 27be2d3566b42fd5-MAA
{"kind": "delivery_quote", "fee": 750, "created": "2016-02-28T18:26:14Z", "expires": "2016-02-28T18:31:14Z", "currency": "usd", "duration": 60, "dropoff_eta": "2016-02-28T19:31:14Z", "id": "dqt_KhBvlVTh8vQ8N-"}
Here ya go. You have to parse the results.
$result = json_decode($result,true); //decodes JSON to associative array
echo $result['fee']; //750
Alternatively, if you want to use an object format
$result = json_decode($result); //decodes JSON to an object
echo $result->fee; //750
EDIT
You also need to set CURLOPT_HEADER to false
This includes response header in output
curl_setopt($process, CURLOPT_HEADER, false);
This is my code:
$url = "https://bitbucket.org/api/2.0/repositories/***/***/pullrequests/35/merge";
$curl1 = curl_init();
curl_setopt($curl1, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt($curl1, CURLOPT_USERPWD, "***:***");
curl_setopt($curl1, CURLOPT_HEADER, true);
curl_setopt($curl1, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl1, CURLOPT_URL, $url);
curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl1, CURLOPT_POST, true);
echo curl_exec($curl1);
Thats the response:
HTTP/1.1 400 BAD REQUEST Server: nginx/1.5.10 Date: Wed, 04 Mar 2015 06:03:15 GMT Content-Type: text/plain Content-Length: 11 Connection: keep-alive X-Served-By: app19 X-Render-Time: 0.0410010814667 Content-Language: de X-Static-Version: 572a80470390 Vary: Authorization, Accept-Language, Cookie X-Version: 1d224fb664b6 ETag: "825644f747baab2c00e420dbbc39e4b3" X-Request-Count: 27 X-Frame-Options: SAMEORIGIN Bad Request
Why does this not work? (For safety reasons i replaced some informations with ***)
You are missing the mandatory parameters for that particular endpoint which should be included in your request body.
According to the API, those mandatory parameters are owner, repo_slug and pull_request_id.
$request_body = array(
'owner' => 'account-name',
'repo_slug' => 'repo-name',
'pull_request_id' => 35
);
Because you specified application/json as your Content-Type, you need to json_encode the array from above:
curl_setopt($curl1, CURLOPT_POSTFIELDS, json_encode($request_body));
As a side note, you could use bitbucket-api library, which can help you to interact with Bitbucket API in a more easy way.
Accepting a pull request using that library, looks something like this:
$pull = new Bitbucket\API\Repositories\PullRequests();
// set your login credentials here
$pull->getClient()->addListener(
new \Bitbucket\API\Http\Listener\BasicAuthListener('username', 'password')
);
$pull->accept($account_name, $repo_slug, 35);
You can read more in the docs.
Disclaimer: I am the author of bitbucket-api library.
I am using Gcm for sending notifications and I have used curl for the same. Here is the script
$registrationId= array('adkbvkasdjb');
$headers=array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$sendData=array(
'msg'=>'any message');
$url= GCM_URL;
$details=array(
'registration_ids'=>$registrationId,
'time_to_live'=> 48*60*60,
'data'=>$sendData,
);
$ch= curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($details));
$result= curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
// closing the curl connection
curl_close($ch);
Now i am getting the header of the response as
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Date: Thu, 16 Jan 2014 11:05:17 GMT
Expires: Thu, 16 Jan 2014 11:05:17 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alternate-Protocol: 443:quic
Transfer-Encoding: chunked
Since I am not very good with regex and i searched a lot about a method that could parse the header of the response but all in vain.
Question:-
So i just wanna know is there anything or any method that could parse the header response as an array ?
Note:- I found a little about http_parse_header() but it need pcre to be installed so i am not sure whether it is installed on my REAL SERVER :)
You don't need any Regex to do it. If you read the first comment of parse_http_headers documentation on php.net, there is a little implementation if pecl_http lib is not found.
Follow the link:
http://www.php.net/manual/en/function.http-parse-headers.php#112986
Okay updated it all. I use this function:
private function get_follow_url($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
if(preg_match('Location:(.*)', $a, $r)){
$url=trim($r[1]);
$this->get_follow_url($url);
}
return $a;
}
I get this when it is echoed:
HTTP/1.1 301 Moved Permanently Server: nginx/0.7.67 Date: Sun, 14 Oct 2012 10:03:21 GMT Content-Type: text/html; charset=UTF-8 Connection: keep-alive X-Powered-By: PHP/5.2.17 X-Pingback: http://thesexguy.com/xmlrpc.php Location: http://example.com/mature Content-Length: 0
So I do a recursion.. and try to fetch the page again after scraping the Location word...
It should take me to http://example.com/mature on the recursion? am I right? But I fail to scrape the location word..why?
You need to either use CURLOPT_FOLLOWLOCATION or set cURL to retrieve full headers (CURLOPT_HEADER) and parse Location headers.