Want to use cURL instead of SimpleXML_load_file() - php

Using below script I can parse API data successfully.
$xml_report_daily=simplexml_load_file("https://api.sitename.com/api/reports/api_get.asp?User=00012345&Key=abcdefghijklmnop&fromDate=11/12/2014&toDate=12/12/2014&mid=25");
foreach ($xml_report_daily as $report_daily):
$trans_id=$report_daily->TRANSID;
$trans_id=$report_daily->MID;
$trans_id=$report_daily->EXT;
$trans_id=$report_daily->USER;
endforeach;
XML data are something like this:
<DATABASE>
<RECORD>
<TRANSID>1348818</TRANSID>
<MID/>
<EXT>0</EXT>
<USER>00012345</USER>
</RECORD>
.
.
.
so on...
</DATABASE>
But I want to use cURL instead of simplexml_load_file. So I used below script but it is not giving any result data.
$url = "https://api.sitename.com/api/reports/api_get.asp?User=00012345&Key=abcdefghijklmnop&fromDate=11/12/2014&toDate=12/12/2014&mid=25";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
$xml = curl_exec($ch);
echo $xml;
Please let me know what I am missing or doing wrong.
Thank you,

Ok, here is my complete answer and hope it will be useful to others.
I used 2 methods to read XML data from specific link.
Method# 1 : Using simplexml_load_file() - allow_url_fopen should be ON on hosting server for this method to work. This method is working fine both on my local as well as actual server.
$xml_report_daily=simplexml_load_file("https://api.sitename.com/api/reports/api_get.asp?User=00012345&Key=abcdefghijklmnop&fromDate=11/12/2014&toDate=12/12/2014&mid=25");
foreach ($xml_report_daily as $report_daily):
$trans_id=$report_daily->TRANSID;
$m_id=$report_daily->MID;
$ext_id=$report_daily->EXT;
$user_id=$report_daily->USER;
echo $trans_id." ".$m_id." ".$ext_id." ".$user_id."<br/>";
endforeach;
Method# 2 : Using cURL - After doing as suggested here, now this method too is working fine both on my local as well as actual server.
$url = "https://api.sitename.com/api/reports/api_get.asp?User=00012345&Key=abcdefghijklmnop&fromDate=11/12/2014&toDate=12/12/2014&mid=25";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
$xml = curl_exec($ch);
$xml_report_daily = simplexml_load_string($xml);
foreach ($xml_report_daily as $report_daily):
$trans_id=$report_daily->TRANSID;
$m_id=$report_daily->MID;
$ext_id=$report_daily->EXT;
$user_id=$report_daily->USER;
echo $trans_id." ".$m_id." ".$ext_id." ".$user_id."<br/>";
endforeach;
When using cURL, I was getting no result data so paul-crovella suggested me to check error. so I used below script and I found that I was trying to acess https (SSL certificate) data as also mentioned by Raffy Cortez
if(curl_exec($ch) === false)
{ echo 'Curl error: ' . curl_error($ch); }
else
{ echo 'Operation completed without any errors'; }
To resolve this https (SSL certificate) related issue, here is very very helpful link and you can use any of methods mentioned there as per your necessity.
HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK
Thank you,

You are calling https URL in your cURL, you need to use
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Related

How to access odata that produced by Nav webservice into html layout using PHP

I try to get odata produced by a navision webservice. When I directly access the url given using chrome browser, the page asks for user name and password and then chrome shows xml data as expected.
But when i use a PHP script, it always returns "1".
My code looks like this:
$url = 'http://103.7.1.182:14048/DynamicsNAV71-6/OData/Company(\'Unit%20G%205\')/Item_Master_on_hand_no_Desc';
$login = 'Gem-gae\senzo1:Bsbsenzo2018';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $login);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/x-www-form-urlencoded',
'Content-Length: ' . strlen(1))
);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
Is there any mistakes with that code ?
Thanks for your help
There's no mistake on your code, it successfully connects to the external server via cURL and retrieves the data.
The value in $output (if you do a var_dump) is true (that's why you see 1 if you echo it).
Said that, the issue is on the server you are contacting (103.7.1.182:14048).
You probably need to send some data or something, I can't tell you exactly what because I don't know what is in that server.
To send data, you can add a curl_setopt line:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
Where $data is an array.

can't scrape data - from httpswebsite

I am trying to get some country name from one of website. that website URL starting with https so i am not able to scrape data. please give me some solution.
Here is my code :
$curl = curl_init('https://testing.co/india');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$page = curl_exec($curl);
if (curl_errno($curl)) {`enter code here`
echo 'Scraper error: ' . curl_error($curl);
exit;
}
curl_close($curl);
$regex = '/<a class="startup-link">(.*?)<\/a>/s';
if (preg_match($regex, $page, $list))
echo $list[0];
else
print "Not found";
Get this error : Scraper error: SSL certificate problem: unable to get local issuer certificate
Today i am solving this problem and i came to know about it.
See. Below is code that is working for me.
// Set so curl_exec returns the result instead of outputting it.<br/>
$url = "https://www.google.co.in/?gws_rd=ssl";<br/>
$ch = curl_init();<br/>
curl_setopt($ch, CURLOPT_URL, $url);<br/><br/>
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br/>
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);<br/>
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);<br/>
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "GeoTrustGlobalCA.crt");
<br/>
// Get the response and close the channel.<br/>
$response = curl_exec($ch);<br/>
$link = fopen("data.txt","w+");<br/>
fputs($link,$response);<br/>
fclose($link);<br/>
curl_close($ch);<br/>
You have pass certificate on this..
On Mozilla firefox left handside of website URL you get one information icon. Then click on Security tab then find View certificate. Click on Details Tab.
See Certificate Hierarchy Section. Click on top most label and see below there is an option as EXPORT. Export that certificate and save the CA certificate to your selected location, making sure to select the X.509 Certificate (PEM) as the save type/format.
e.g.
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "GeoTrustGlobalCA.crt");
Now save it and run.. You will get the data..
use
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false)

Adding events via places return 404 error:

Please excuse my terminology if I get anything wrong, I'm new to Google API
I'm trying to add events via the Places API, for a single venue (listed under the bar category). I've followed the instructions here:
https://developers.google.com/places/documentation/actions?utm_source=welovemapsdevelopers&utm_campaign=places-events-screencast#event_intro
and this is the URL I am posting to (via PHP)
https://maps.googleapis.com/maps/api/place/event/add/format?sensor=false&key=AIzaSyAFd-ivmfNRDanJ40pWsgP1 (key altered)
which returns a 404 error. If I have understood correctly, I have set the sensor to false as I am not mobile, and created an API key in Google apis, with the PLACES service turned on.
Have I missed a vital step here, or would a subsequent error in the POST submission cause a 404 error? I can paste my code in but I thought I'd start with the basics.
Many thanks for your help, advice and time. It's very much apprecciated.
I've added this line to my CurlCall function which I believe should specify a POST, and the result is still the same.
curl_setopt($ch, CURLOPT_POST, 1);
so the whole functions reads
function CurlCall($url,$topost)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $topost);
$body = curl_exec($ch);
curl_close($ch);
echo $body;
echo '<br>';
echo 'URL ' . $url;
echo '<br>';
return $body;
}
Are you sure that you are using the POST method and not GET?
You need to specify the format of your request in the URL by changing the word format to either json or xml depending on how you are going to structure and POST your request.
XML:
https://maps.googleapis.com/maps/api/place/event/add/xml?sensor=false&key=your_api_key
JSON:
https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=your_api_key

Unable to retrieve and save user’s display picture through cURL

I am trying to retrieve users display picture through graph api and using cUrl to save it into the disk, but am unable succeed in it and getting this error when trying to check the mime type of the picture that I saved:
Notice: exif_imagetype(): Read error! in
//$userPpicture = $user_profile[picture];
//Create image instances
$url = "http://graph.facebook.com/{$userId}/picture?type=large";
$dpImage = 'temp/' . $userId . '_dpImage_' . rand().'.jpg';
echo $dpImage;
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data($url);
file_put_contents($dpImage, $returned_content);
echo "Type: " . exif_imagetype($dpImage);
for this updated code using curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); I am getting this error:
Warning: curl_setopt(): CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in /var/fog/apps/app12345/myapp.phpfogapp.com/start.php on line 178
If this action requires any server side configuration then i might not be able to do this as am using a shared cloud storage over phpfog.
Kindly help me with this.
Thankyou.
The graph url you are using of http://graph.facebook.com/4/picture?type=large returns a HTTP 302 redirect, not the actual user image. You would need to follow the redirect and download the image at that url which is a url that looks like this: http://profile.ak.fbcdn.net/hprofile-ak-snc4/49942_4_1525300_n.jpg
As OffBySome points out, you need to follow the 302 redirect served by graph.facebook.com to the final destination, which contains the actual image data.
The simplest way to do that in this case is to add another curl_setopt call with CURLOPT_FOLLOWLOCATION as true. i.e.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true)
Check out http://us3.php.net/manual/en/function.curl-setopt.php for more details.

Why does cURL always return a status code?

I have some PHP code that calls into the cURL library. I'm using it to get JSON data.
I have set cURL opt 'CURLOPT_RETURNTRANSFER' to 1, but still get status code..
Code follows:
<?php
function fetch_page($url)
{
$ch = curl_init();
$array = array(
'include'=>'ayam'
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
$return = fetch_page(MY_LINK_URL);
echo json_decode($return);
?>
The code looks totally correct. Try var_dump($result) before returning it to see what it is exactly.
Also, set CURLOPT_HEADER to 1 and check the view source of the output in your browser; both of these can help debug the issue. Edit the question and post the results if so we can help more effectively.
Update: Since you are using HTTPS, also add
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
That looks correct. I actually have the same problem, but when I added
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
it returns json code correctly instead of returning 1(True).
According to the PHP docs,
Returns TRUE on success or FALSE on
failure. However, if the
CURLOPT_RETURNTRANSFER option is set,
it will return the result on success,
FALSE on failure.
So that means you should get
success: the result
failure: FALSE (which is echoed as 0)
Also, if you are fetching JSON, and need to access it, use json_decode() not json_encode().
Well, you should tell us wich url you're pointing (and wich version of php you are running).
I've tried with php 5.3 on "www.google.com" and it worked as expected ($result contains the whole webpage)
Might of had a similar problem:
- cURL on local dev network problem with virtual host naming
Before you close your curl handle output this:
$result = curl_exec ($ch);
print_r(curl_getinfo($ch));
curl_close ($ch);
Here was my solution for getting around the virtual host
// This is your Virtual Hosts name
$request_host = 'dev.project';
// This is the IP
$request_url = '192.168.0.1';
$headers = array("Host: ".$request_host);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $request_url.'?'.$request_args);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
There seems to be a number of reasons why CURLOPT_RETURNTRANSFER can be ignored, and SSL certificate checking is only one of them:
In my case the culprit was CURLOPT_POST which I had set to true. I was expecting to get back a string consisting of the HTTP response header plus the response itself. Instead I was getting status code 1. Go figure. Thankfully I did not need the HTTP header so the solution for me was:
curl_setopt($ch, CURLOPT_HEADER, false);
If I did need the header info, I don't know what I would do. I've wasted an insane amount of time tracking down the problem.
Damn you PHP curl! (waves fist in anger)

Categories