getting JSON object from a GET cURL in php - php

Here is my code:
$ch = curl_init('');
$request = 'where={"place":"'.$place.'"}&count=1&limit=0';
$url = "https://api.parse.com/1/classes/className" . "?" . $request;
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-Parse-Application-Id: ...',
'X-Parse-REST-API-Key: ...
));
//curl_setopt($ch, CURLOPT_POST, true);
// Execute
$result = curl_exec($ch);
// Close connection
curl_close($ch);
Here is the output:
{"results":[],"count":0}
I want to get only he number in count.
I tried this:
$json_res = json_decode($result, true);
echo 'Number : '.$json_res['count'];
but the output becomes:
Number :
If i do json_encode the result is just a True value.
I tried added this:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
but didn't change anything.
What am I missing?
EDIT: doing a var_dump on $json_res gives me that: int(1).
Why is that?

Curl does not return the output if you don't set the CURLOPT_RETURNTRANSFER option
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Related

Walmart API Search Products

I am trying to get search products for a keyword
My code:
$searchquery = "ipod";
$api_endpoint = "http://api.walmartlabs.com/v1/search";
$postfields = "apiKey=". $appid ."&query=" . $searchquery;
//$postfields = array('apiKey' => $appid, 'query' => $searchquery);
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, $api_endpoint);
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
//curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connection, CURLOPT_POST, true);
curl_setopt($connection, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($connection, CURLOPT_HEADER, true);
//curl_setopt($connection, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($connection);
curl_close($connection);
print_r($api_endpoint);
print_r($response);
When i go in browser and visit api.walmartlabs.com/v1/search?apiKey={appid}&query=ipod , it shows results, but when i try to do with curl , it shows
"Action Not Found"
Here is the Screenshot
Any help would be appreciated.
looking on the doc (https://developer.walmartlabs.com/io-docs) it appears that the server expects a GET request.
Just replace your POST request with a GET request and all should be fine
$searchquery = "ipod";
$api_endpoint = "http://api.walmartlabs.com/v1/search";
$urlParams = "apiKey=". $appid ."&query=" . $searchquery;
$fullUrl = $api_endpoint . '?' . $urlParams;
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, $fullUrl);
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($connection, CURLOPT_HEADER, true);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($connection);
curl_close($connection);
print_r($api_endpoint);
print_r($response);
<?php
ini_set('display_errors', 1);
//API URL : https://affiliates.walmart.com/#!/api
$api_key="**********"; //https://developer.walmartlabs.com/apps/mykeys
$keywords="men%20watches"; // Search text - whitespace separated sequence of keywords to search for
$format="json"; // data we want in response
$responseGroup="base"; // Specifies the item fields returned in the response, allowed response groups are [base, full]. Default value is base.
$sort='price'; //Sorting criteria, allowed sort types are [relevance, price, title, bestseller, customerRating, new]. Default sort is by relevance.
$order="asc"; //Sort ordering criteria, allowed values are [asc, desc]. This parameter is needed only for the sort types [price, title, customerRating].
//http://api.walmartlabs.com/v1/search?apiKey={apiKey}&lsPublisherId={Your LinkShare Publisher Id}&query=ipod
$request_url="http://api.walmartlabs.com/v1/search?apiKey=".$api_key."&query=".$keywords."&format=".$format."&responseGroup=".$responseGroup."&sort=".$sort."&order=".$order;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$request_url);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$retValue = curl_exec($ch);
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}
curl_close($ch);
$arr = json_decode($retValue,true);
echo "<pre>";
print_r($arr);
// echo "<pre>";
// var_dump($retValue);
?>

get data from URL using file_get_contents and cURL

I am using codeigniter framework.
I want to retrieve the data from the URL provided. I already tried this answers: tried.
Problem is that when i access the url that time it is printing the data. but when i try it with file_get_contents function, it is not going to print any data.
<?php
$url ='https://test.com/getSessionData';
$test = file_get_contents($url);
$t = json_decode($test);
var_dump($t);
?>
That url returns json data like:
{
"email": "test#t.com",
"LOGIN": true,
"name": "testing",
"logintype": "ca"
}
Also tried using cURL:
<?php
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$curl_response = curl_exec($curl);
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);
?>
But it is not working and it returns empty. i have checked that allow_url_fopen is on.
This might helpful
http://php.net/manual/en/migration56.openssl.php
So code looks like this:
<?php
$arrContextOptions=array(
"ssl"=>array(
"cafile" => "/path/to/bundle/ca-bundle.crt",
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents("https://test.com/getSessionData", false, stream_context_create($arrContextOptions));
echo $response; ?>
This is the class I said:
/**
* Created by PhpStorm.
* User: rain
* Date: 15/11/2
* Time: 下午4:08
*/
class MyCurlLibrary{
public static function getRequest($url,Array $data=array(),$isNeedHeader=0){
$ch = curl_init();
if($data){
$bindQuery = http_build_query($data);
$url.="?".$bindQuery;
}
curl_setopt($ch, CURLOPT_URL, $url);
//if need return
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//this is for https
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, $isNeedHeader);//if contains header
//this is for web redirect problem
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
public static function postRequest($url,Array $data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post Data
curl_setopt($ch, CURLOPT_POST, 1);
// post variable
if($data){
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$output = curl_exec($ch);
curl_close($ch);
//return data
return $output;
}
}
/**
* sample
*
* //test Data
$url = "http://localhost:8080/test/test.php";//改文件有代码 print_r($_GET); print_r($_POST)
$data = array('a'=>'b','c'=>'d',8=>666,888);
//test get function
$result = MyCurl::getRequest($url,$data);
//test post function
$result = MyCurl::postRequest($url,$data);
//print result
var_dump($result);
*
*
*/

Fetching xml with curl on https

So I made a login to site like this:
$ch = curl_init('https://emea2cps.adobeconnect.com/api/xml?action=login&login=username&password=password');
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
curl_exec($ch);
$info= curl_getinfo($ch);
echo 'passed' . $info['total_time'] . ' secconds ' . $info['url'] . '------ and http-code'. $info['http_code'];
print curl_error($ch);
After I want to fetch XML of my meetings by this link https://meet77842937.adobeconnect.com/api/xml?action=report-my-meetings
I tried the following code:
$ch1 = curl_init('https://meet77842937.adobeconnect.com/api/xml?action=report-my-meetings');
curl_setopt($ch1,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch1, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch1, CURLOPT_SSLVERSION,3);
curl_setopt($ch1,CURLOPT_RETURNTRANSFER,TRUE);
$data = curl_exec($ch1);
$info1= curl_getinfo($ch1);
echo 'passed' . $info1['total_time'] . ' secconds ' . $info1['url'] . '------ and http-code'. $info1['http_code'];
print curl_error($ch1);
curl_close($ch1);
curl_close($ch);
$xml = new SimpleXMLElement($data);
print_r($xml);
What can you advise me?
Note: i can see xml when i input this link on browser
Structure:
<results>
<status code="ok"></status>
<my-meetings>
<meeting sco-id="1282590819" type="meeting" icon="meeting" permission-id="host" active-participants="0">
<meeting sco-id="1282620938" type="meeting" icon="meeting" permission-id="host" active-participants="0">
</my-meetings>
</results>
Output:
like this for ex:
sample1aksamaimeet77842937.adobeconnect.com/sample1/2014-02-28T06:15:00.000-08:002014-02-28T07:15:00.000-08:00false01:00:00.000sample2meet77842937.adobeconnect.com/sample2/2014-02-28T06:15:00.000-08:002014-02-28T07:15:00.000-08:00false01:00:00.000
Try adding this:
curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, FALSE);
Also:
$data = curl_exec($ch1); // after this line
var_dump(htmlentities($data)); // add this one
to see what's the output. It'll give you a starting point to debug.
UPDATE
Add:
curl_setopt($ch, CURLOPT_COOKIEFILE, __DIR__.'/cookies');
curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__.'/cookies');
// repeat this for all $ch, $ch1, $ch2 and such where you need auth cookie available
to store the login information and reuse it in other requests. Your error shows your second request goes unauthenticated. So I assume first one sets a cookie for login unless you need to carry over a variable returned by the first login sequence.
AND remove the \ in password\. Your password has an extra character that should not be there!
Working code:
// Login.
$ch = curl_init('https://emea2cps.adobeconnect.com/api/xml?action=login&login=username&password=password');
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_COOKIEFILE, __DIR__.'/cookies');
curl_setopt($ch,CURLOPT_COOKIEJAR, __DIR__.'/cookies');
$data = curl_exec($ch);
var_dump($data);
curl_close($ch);
// Query.
$ch = curl_init('https://meet77842937.adobeconnect.com/api/xml?action=report-my-meetings');
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_COOKIEFILE, __DIR__.'/cookies');
curl_setopt($ch,CURLOPT_COOKIEJAR, __DIR__.'/cookies');
$data = curl_exec($ch);
var_dump($data);
curl_close($ch);
Read it. It's clear enough.

Posting JSON data to API using CURL

When I'm posting json data to API using curl - I'm not getting any output. I would like to send email invitation to recipient.
$url_send ="http://api.address.com/SendInvitation?";
$str_data = json_encode($data);
function sendPostData ($url, $post) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
return curl_exec($ch);
}
And here is JSON $str_data
[
{
"authorizedKey" : "abbad35c5c01-xxxx-xxx",
"senderEmail" : "myemail#yahoo.com",
"recipientEmail" : "jaketalledo86#yahoo.com",
"comment" : "Invitation",
"forceDebitCard" : "false"
}
]
And calling function:
$response = sendPostData($url_send, $str_data);
This is the API: https://api.payquicker.com/Help/Api/POST-api-SendInvitation
Try adding curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
And changing http_build_query($post) to $post
The implementation:
<?php
$data = array(
"authorizedKey" => "abbad35c5c01-xxxx-xxx",
"senderEmail" => "myemail#yahoo.com",
"recipientEmail" => "jaketalledo86#yahoo.com",
"comment" => "Invitation",
"forceDebitCard" => "false"
);
$url_send ="http://api.payquicker.com/api/SendInvitation?authorizedKey=xxxxx";
$str_data = json_encode($data);
function sendPostData($url, $post){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
}
echo " " . sendPostData($url_send, $str_data);
?>
The response I get is:
{"success":false,"errorMessage":"Object reference not set to an instance of an object.","status":"N/A"}
But maybe it will work with valid data....
Edit:
For posting xml,
it's the same as on their site, except in a string:
$xml = '
<SendInvitationRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PQApi.Models">
<authorizedKey>80c587b9-caa9-4e56-8750-a34b17dba0a2</authorizedKey>
<comment>sample string 4</comment>
<forceDebitCard>true</forceDebitCard>
<recipientEmail>sample string 3</recipientEmail>
<senderEmail>sample string 2</senderEmail>
</SendInvitationRequest>';
Then:
sendPostData($url_send, $xml)
You have to add header:
$headers= array('Accept: application/json','Content-Type: application/json');
And:
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Otherwise ...
HTTP Status 415 - Unsupported Media Type
... may happen.
You don't need to add headers as you already do json_encode.
just print_r (curl_getinfo($ch)); and see the content type info in it.

Scripts after doing cURL don't work. Page is reloaded continuously

These are the steps I want to do:
Get the HTML code of http://www.skyscanner.es/ , a search of flights.
Get only some part of that HTML: a specific "span" which has the price.
Operate with it.
This is the PHP code what I do:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "from=Bilbao (BIO)&to=Barcelona (BCN)&depdatetext=25/03/2013&sc_returnOrOneWay=2");
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>
But I get a strange string like this:
‹¥TkoÚ0ý^‰ÿpTi“ê< t%<¤RuR»U+{}4ñ…X5qf›×Pÿûì$ZõÛ‚Äu¬sî=çú:ýÓ믣Éï‡1¤f!àáû§»Ï#ðHül‚àzr ¿n'÷wù!<Åã/x©1yëõÚ_·}©æÁä[°qY"G«–DŸæ 'ý¢Êf!2=x#CÔívKb FÊ\\ ¡àÐÿ,ùjàdf03d²Íу¤|x7&pì$)UÍ€kI®®:]yKe¸8¼;#àv2y€ª),520h’ Ö`R®!§s3i€ !×Èü~Pòm"m¶ÁXUÝDëBô)!“©dÛÝ‚ª9Ïâ°7³‰æ1ö?à¢|ÑÛø*F3z§ânQ¬ÐðÄîhši¢QñYoJ“§¹’ËŒÅÍqñôž'3Ž‚Y“»œ2ƳyBÔÉ7…îÏ®zÏÐ8I£Ý¡~Ë¿°ja‰RÅÍ››—/m!£BêkähÚ§ÌÛ~nÐEýÐýö´0¬iMw¨¨vkÎLw/ÏêeoæÒ&iA^ôÌ3 §Ë$E÷Þ9Ô=<êØ‘3{uûHµß)gºYMÏî…[1—š.³X¡ †¯Ð¡ý M\¤<³FŽÏÆ•{mŒ™ÇWö0öÆ\{ÞÎNˆ ­bµ¿nœ\d|œÙ›SôÐöÓhøˆÊÎ0Œ•’Ê2¢a?°°ct¥ÙM'›‰ Z×û/6á~¦úië?®Š%—IÚÃIŠ%h+—#‚òÉöfRAB3Gœ"0®sA·¶Àj+Í€g+*8ûH%ƒwµ”÷°¦ú Ç\ä¦ÒåÊ·¿Aí¨îK÷m-¾vñà-ú¡
So, I have not even passed the first step!
I tried to fix it in several ways but I don't know yet what I am doing wrong. I imagine that can be:
The request because I don't add how much adult, children...
The CURLOPT_URL has to be www.skyscanner.es/search.html as the form has in the action.
Not do a POST request, do an cURL directly to an URL like http://www.skyscanner.es/flights/bio/bcn/130325/airfares-from-bilbao-to-barcelona-in-march-2013.html?flt=1
Please can anyone help me?
Thanks in advance!
Edited: I've changed the title, is closer to the problem I have now.
It doesn't matter what message is encoded in the body since you're receiving:
HTTP/1.1 405 Method Not Allowed
which means you can't use POST.
If you'll read all the headers of the response you'll see that one of them says:
Allow: GET, HEAD, OPTIONS, TRACE
If you'll remove the two lines:
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "from=Bilbao (BIO)&to=Barcelona (BCN)");
and change:
curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/");
into:
curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/vuelos/bio/bcn/130325/tarifas-de-bilbao-a-barcelona-en-marzo-2013.html");
It'll work.
Checkout the following code:
<?php
$accept = array(
'type' => array('application/rss+xml', 'application/xml', 'application/rdf+xml', 'text/xml'),
'charset' => array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'byte2be', 'byte2le', 'byte4be', 'byte4le', 'BASE64', 'UUENCODE', 'HTML-ENTITIES', 'Quoted-Printable', '7bit', '8bit'))
);
$header = array(
'Accept: '.implode(', ', $accept['type']),
'Accept-Charset: '.implode(', ', $accept['charset']),
);
$encoding = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/vuelos/bio/bcn/130325/tarifas-de-bilbao-a-barcelona-en-marzo-2013.html?flt=1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt ($ch, CURLOPT_POST, 1);
// curl_setopt ($ch, CURLOPT_POSTFIELDS, "from=Bilbao (BIO)&to=Barcelona (BCN)");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$response = curl_exec($ch);
curl_close($ch);
if (!$response) {
// error fetching the response
} else {
echo $response;
}
?>
I thought that it was using POST method because I get a page whithout prices.
Now I realize that the URL were relatives, so scrips were not loaded. I've add base tag.
[code before]
$result = str_replace("<head>", "<head><base href=\"$skyScannerURL\" />", $response);
Now it has styles and try to load something, but it enter in a bucle, the page is reloaded and the URL has a parameter increasing, it is: ?crty=107
The full code:
$accept = array(
'type' => array('application/rss+xml', 'application/xml', 'application/rdf+xml', 'text/xml'),
'charset' => array_diff(mb_list_encodings(), array('pass', 'auto', 'wchar', 'byte2be', 'byte2le', 'byte4be', 'byte4le', 'BASE64', 'UUENCODE', 'HTML-ENTITIES', 'Quoted-Printable', '7bit', '8bit'))
);
$header = array(
'Accept: '.implode(', ', $accept['type']),
'Accept-Charset: '.implode(', ', $accept['charset']),
);
$encoding = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/vuelos/bio/bcn/130325/tarifas-de-bilbao-a-barcelona-en-marzo-2013.html?flt=1");
//curl_setopt($ch, CURLOPT_URL, "http://www.skyscanner.es/flights/bio/bcn/130325/airfares-from-bilbao-to-barcelona-in-march-2013.html?flt=1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$response = curl_exec($ch);
curl_close($ch);
if (!$response) {
// error fetching the response
} else {
$skyScannerURL = 'http://www.skyscanner.es/';
$result = str_replace("<head>", "<head><base href=\"$skyScannerURL\" />", $response);
echo $result;
}
You can see online here: codepad.viper-7.com
Obvious something is not working well.
Thanks again everyone.

Categories