using json data from Curl response - php

Hi I'm a little new at CURL, but I'm trying to request some json data and then parse the results. I am having success with retrieving the data, but I can't handle the response. Here's the code
function bitBucketCurl($url)
{
global $bitPassword;
global $bitUsername;
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$bitUsername:$bitPassword");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$commitinfo = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
return $commitinfo;
}
$json = bitBucketCurl($url);
echo $json; // This seems to work in that, when I load the page, I can see the json data
//turn json data into an array - this is what does not seem to be working
$obj_a = json_decode($json, true);
print_r ($obj_a); //the result is simply a 1 rather than the array I would expect
The basic problem is the json data shows up when I echo $json but when I try to turn that data into an array it doesn't work. When I print the array, I just get a '1'.

I got the required result by adding the following line:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

Related

Open a URL with a PHP within it using cURL

I am trying to fetch data from a URL using cURL...this is something I would be able to do but the URL that I want to fetch data from has a section of php code within it - i.e. the URL is populated using a values generated by an earlier section of code.
I want to access the URL, take the figures out of it and then plug those figures into something else. At the minute I am hitting a bit of a roadblock as the php doesn't populate the URL...any ideas?
The code I am using is:
$url = "https://*START OF API ADDRESS*<?php echo $request_ids; ?>*END OF API ADDRESS*";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
//var_dump(json_decode($result, true));
$rates = json_decode($result, true);
// Save result
$rates['last_updated'] = time();
file_put_contents($file, json_encode($rates));
}

How to extract data from a decoded JSON object in php

I wanted to try to get data from a JSON string which is loaded from another page. I currently have used Curl to get the data from the webpage but I can't acces the data in it.
I've already tried:
var_dump(json_decode($result->version, true));
var_dump(json_decode($result[3][0]["date"], true));
But this does't seem to work as it always returns NULL
$url="https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
First decode the JSON, then get the properties you want. Like this:
$yourObject = json_decode($result);
var_dump($youObject->version);
this is working for me.
<?php
$url = "https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
// Execute
$result = curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
$data = json_decode($result);
//echo $data->data[0]['date'];
echo "<pre>";
print_r($data->data[0]->date);
}
?>
if you want to get date of all index then try this in loop.
Firstly if your using GET there is no need to use CURL,
$result = file_get_contents(https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201);
Will work just as well without any of the overhead. I suspect that your CURL isn't returning the page content so using file_get_contents() will fix it.

JSON text unparseable when using cURL to grab it?

I have this really long JSON string: http://pastebin.com/2jJKSGHs , which is being pulled from a music API.
I have this code set up to parse it ( http://pastebin.com/EuJtuhHg ):
$url = "https://api.discogs.com/database/search?type=artist&q=pink[keyandsecretredacted]";
//initialize the session
$ch = curl_init();
//Set the User-Agent Identifier
curl_setopt($ch, CURLOPT_USERAGENT, 'YourSite/0.1 +http://your-site-here.com');
//Set the URL of the page or file to download.
curl_setopt($ch, CURLOPT_URL, $url);
//Ask cURL to return the contents in a variable instead of simply echoing them
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Execute the curl session
$output = curl_exec($ch);
//close the session
curl_close ($ch);
//decode and print output
$output = json_decode($output2, true);
echo($output['results'][0]['title']);
When I insert the contents of the JSON string directly into my code, the json_decode works perfectly on it. But when I try to grab it from the API using the method above, nothing prints on my page -- it's just empty. Printing out json_last_error returns "0", so it's not detecting any errors.
Any ideas why this might be happening?
Replace
$output = curl_exec($ch);
with
$output2 = curl_exec($ch);
Otherwise $output2 isn't defined, and json_decode is using an undefined variable:
$output = json_decode($output2, true);

How to use GET on an external URL

I am using an API that returns JSON from a GET request
Eg.
https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}
Returns
{
"call_duration": 4,
"total_amount": "0.00400"
}
How can I call this page from within a script and save call_duation and total_amount as separate variables?
Something like the following?:
$call_duration =
$_GET[https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}, 'call_duration'];
$_GET[] contains the get parameters that are passed to your code - they don't generate a GET request.
You could use curl to make your request:
$ch = curl_init("https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$result = json_decode($output);
If PHP has allow_url_fopen enabled you can simply do
json_decode(file_get_contents('https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}'))
Otherwise you'll have to resort to using something like Curl to get the request going. $_GET is a superglobal array which doesn't actually do anything. It only contains what the script was started with. It does not make any requests itself.
Use curl to get the JSON, then json_decode to decode it into PHP variables
$auth_id = 'your auth id here';
$call_uuid = 'your call_uuid here';
// initialise curl, set URL and options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.domain.com/v1/Account/{$auth_id}/Call/{$call_uuid}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// get the response and decode it
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
$call_duration = $response['call_duration'];
$total_amount = $response['total_amount'];

sending xml string using php curl but not as post parameter

:)
I'm trying to send an XML using curl but not as post parameter. what I mean is this.
for example.
the receiving side of that XML won't be able to recieve the XML using $_POST variable.
he will need to use the following code:
$xmlStr=null;
$file=fopen('php://input','r');
$xmlStr=fgets($file);
I want to be able to send an xml string using curl via https.
so the following would be wrong:
public static function HttpsNoVerify($url,$postFields=null,$verbose=false) {
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($postFields !=null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
if ($verbose) {
curl_setopt($ch, CURLOPT_VERBOSE, 1);
}
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
because here i can use HttpsNoVerify($url,array('xml_file'=>'xml..')); and that
will paste it as post parameter. and i want it as post output.
so please I hope i explained myself properly and I explained exactly what I don't want to do.
how can I do what i want to do?
thanks! :)
kfir
Just directly pass the xml string as second parameter instead of an associative array item,
HttpsNoVerify($url, 'xml ..');
This will eventually call
curl_setopt($ch, CURLOPT_POSTFIELDS, "xml ...");
Which will be put in php://input for the remote server.

Categories