Get api result from URL using PHP - php

The following URL is from the FobBugz API documentation:
https://kakapo.fogbugz.com/api.asp?cmd=search&q=project:inbox%20assignedTo:Elinor&cols=ixProject,ixPersonAssignedTo,sTitle&max=2&token=04t9123822q4kbba09nt740inhibk2 (you can find it here)
If I copy and paste the above URL into a web browser I get an XML response. What I would like to do is create a function that returns the XML response as a its result.
I am so stuck, it is simply not working. All I seem to get in response is an empty string. When I use this 'example' on the FogBugz site I get XML telling me that I am NOT logged in.
The function below comes mostly from here: Make a HTTPS request through PHP and get response I have been messing with it for hours without success.
function searchBug(){
$data = "https://kakapo.fogbugz.com/api.asp?cmd=search&q=project:inbox%20assignedTo:Elinor&cols=ixProject,ixPersonAssignedTo,sTitle&max=2&token=04t9123822q4kbba09nt740inhibk2";
//echo $data;
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, False);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
}
[EDIT: in response to comment]
The response that I want to receive is:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<response>
<error code="3">
<![CDATA[ Not logged in ]]>
</error>
</response>
As that is what is shown in my browser when I paste the URL and press enter.

You can do it like below:-
<?php
function searchBug($path){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
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);
curl_close($ch);
return $retValue;
}
$sXML = searchBug('https://kakapo.fogbugz.com/api.asp?cmd=search&q=project:inbox%20assignedTo:Elinor&cols=ixProject,ixPersonAssignedTo,sTitle&max=2&token=04t9123822q4kbba09nt740inhibk2');
header('Content-Type: text/xml');
echo $sXML;
Output:- http://prntscr.com/f5fj44

Related

Parsing XML Response with xml schema

Edit
The code given below will work in localhost as it is, if anyone want to copy and try it.The given credentials are valid.
I have a php code which requests data from an API service. An XML request is sent and in response XML data is recieved. I have stored the respose data in a variable $output. When doing echo $output, the details in the XML response is printed. But now I need to parse this response and store the required data in variables. E.g: I need to save $customer_id = value from the <customer_id>12345</customer_id>. I did a thorough google search and tried all the snippets provided by different developers, but no use.
I tried var_dump(simplexml_load_string($output)); and it is returning object(SimpleXMLElement)#1 (0) { }. I even tried converting the XML data to array.
index.php
<?php
$appId ="MFS149250";
$appPass ="5TEBRPCZ";
$brokeCode ="ARN-149250";
$iin = "5011217983";
$xml_data = '<?xml version="1.0" encoding="UTF-8"?>
<NMFIIService>
<service_request>
<appln_id>'.$appId.'</appln_id>
<password>'.$appPass.'</password>
<broker_code>'.$brokeCode.'</broker_code>
<iin>'.$iin.'</iin>
</service_request>
</NMFIIService>';
$URL = "https://uat.nsenmf.com/NMFIITrxnService/NMFTrxnService/IINDETAILS";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
//echo "<textarea>".$output."</textarea>";
echo $output;
var_dump(simplexml_load_string($output));
curl_close($ch);
?>

How to retrieve only one string from a cURL response

I am using the following code to get information about a repo using the Github API.
I am using cURL, but I'm not sure how to just get the name of the repository. So, how can I get just one string from the response and echo that without echoing the complete response? I tried doing $data['name'] but that didn't work.
code:
$ch = curl_init();
curl_setopt($ch,CURLOPT_USERAGENT,'Content-type: application/json');
curl_setopt($ch, CURLOPT_URL, 'https://api.github.com/repos/ruby/ruby');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
This request returns JSON, so just use json_decode.
$jsonStr = curl_exec($ch);
curl_close($ch);
$json = json_decode($jsonStr, true);
var_dump($json['name']);
var_dump($json['full_name']);
It should be trivial from here to get the elements you're interested in.

How to encode token using curl

STEP - 1
I am sending a xml request using CURL and its returning "TOKEN" to me. Please find the below code here:
<root><request><type>mykey</type><username>myusername</username><password>mypassword</password></request></root>
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $curl_url);// passing API URL here
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $xml_strign); // passing xml as a string
$result = curl_exec ($curl_handle);
In this above code executing fine and returning Token as a result.
STEP - 2
In second step, I have to send above token to get my result but not getting result.Please find the below code:
$xml = "<root>
<request>
<type>myparam</type>
<token>lGcvdOnetuxK0paE+AIxE93GB85DURIpOeoBw8quqOs=</token>
</request>
</root>";
curl_setopt($curl_handle, CURLOPT_URL, $curl_url);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $xml);
$result = curl_exec ($curl_handle);
curl_close ($curl_handle);
print_r($result);
May be this Token is contains special charter as i guess, so that I am not getting result. I have seen console url response status in browser its 200 ok.
I do appreciate advance for your help.
I think you have a problem with your post data. You should read details about CURLOPT_POSTFIELDS here :
http://php.net/manual/fr/function.curl-setopt.php
So your xml variable should probably be defined like this:
$xml = array("token" => "lGcvdOnetuxK0paE+AIxE93GB85DURIpOeoBw8quqOs");
At least it should be an array.

Send POST request with empty response

I am trying to get response form my API via CURL, the method needs to get user data via XML and than returns XML with response data.
I get nothing back. API works well, when I try the same request elsewhere than in PHP, it works. My API requires the data to be sent in application/xml Content-Type.
Any ideas what I am doing wrong?
<?php
$request="https://api.mydomain.com/operation/v1/rest/xml/user/authenticate";
$xml_data='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<userCredentials>
<userName>name</userName>
<password>password</password>
</userCredentials>';
$ch = curl_init();
//curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_URL, $request);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, "Content-type: application/xml");
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo "<b>Request:</b> $request <br/>";
echo "<b>Response:</b><pre>".$output."</pre>";
?>
As commented, quick guess (lengthy comment):
echo "<b>Response:</b><pre>".$output."</pre>";
This will output the XML unescaped. Your browser will not display anything inside the browser window, but you should be fine to see something when you view the source of the page.

php - using curl to consume this web service

I saw this post on consuming a web service using CURL: Consume WebService with php
and I was trying to follow it, but haven't had luck. I uploaded a photo of the web service I'm trying to access. How would I formulate my request given the example below, assuming the URL was:
https://site.com/Spark/SparkService.asmx?op=InsertConsumer
I attempted this, but it just returns a blank page:
$url = 'https://xxx.com/Spark/SparkService.asmx?op=InsertConsumer?NameFirst=Joe&NameLast=Schmoe&PostalCode=55555&EmailAddress=joe#schmoe.com&SurveyQuestionId=76&SurveyQuestionResponseId=1139';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$xmlobj = simplexml_load_string($result);
print_r($xmlobj);
Really, you should probably look at the SOAP extension. If it is not available or for some reason you must use cURL, here is a basic framework:
<?php
// The URL to POST to
$url = "http://www.mysoapservice.com/";
// The value for the SOAPAction: header
$action = "My.Soap.Action";
// Get the SOAP data into a string, I am using HEREDOC syntax
// but how you do this is irrelevant, the point is just get the
// body of the request into a string
$mySOAP = <<<EOD
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope>
<!-- SOAP goes here, irrelevant so wont bother writing it out -->
</soap:Envelope>
EOD;
// The HTTP headers for the request (based on image above)
$headers = array(
'Content-Type: text/xml; charset=utf-8',
'Content-Length: '.strlen($mySOAP),
'SOAPAction: '.$action
);
// Build the cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $mySOAP);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Send the request and check the response
if (($result = curl_exec($ch)) === FALSE) {
die('cURL error: '.curl_error($ch)."<br />\n");
} else {
echo "Success!<br />\n";
}
curl_close($ch);
// Handle the response from a successful request
$xmlobj = simplexml_load_string($result);
var_dump($xmlobj);
?>
The service requires you to do a POST, and you're doing a GET (curl's default for HTTP urls) instead. Add this:
curl_setopt($ch, CURLOPT_POST);
and add some error handling:
$result = curl_exec($ch);
if ($result === false) {
die(curl_error($ch));
}
This is the best answer because using this once you need to login then
get some data from webservices(third party site data).
$tmp_fname = tempnam("/tmp", "COOKIE"); //create temporary cookie file
$post = array(
'username=abc#gmail.com',
'password=123456'
);
$post = implode('&', $post);
//login with username and password
$curl_handle = curl_init ("http://www.example.com/login");
//create cookie session
curl_setopt ($curl_handle, CURLOPT_COOKIEJAR, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $post);
$output = curl_exec ($curl_handle);
//Get events data after login
$curl_handle = curl_init ("http://www.example.com/events");
curl_setopt ($curl_handle, CURLOPT_COOKIEFILE, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($curl_handle);
//Convert json format to array
$data = json_decode($output);
echo "Output : <br> <pre>";
print_r($data);
echo "</pre>";

Categories