Sending Responce - PHP API - php

I have built a custom api using php, its a simple api that works by posting xml data.
The code that I have working to post to the api is:
<?php
$xml_data = '<document>
<first>'.$first.'</first>
<last>'.$last.'</last>
<email>'.$email.'</email>
<phone>'.$phone.'</phone>
<body>TEST</body>
</document>';
$URL = "url";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
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);
curl_close($ch);
$Response = curl_exec($ch);
curl_close($ch);
echo "Responce= ".$responce;
?>
On the other side, the code the above posts to:
<?php
$postdata = file_get_contents("php://input");
$xml = simplexml_load_string($postdata);
$first = $xml->first;
$last = $xml->last;
$email = $xml->email;
$phone = $xml->phone;
?>
Then I take those php variables and send to a database.. ALL THIS CODE IS WORKING!!
But my questions is: How do I send a response back to the posting side?
How do I use curl_init to send to curl_exec?
Any help would be great! Thank you
Jason

I think you want:
echo "Responce= ".$Response;
^^^

To return a response you'd do the same as you would for any other content, set a header and echo your output. For example, to return an xml response, from the script handling the post data do the following
<?php
$postdata = file_get_contents("php://input");
$xml = simplexml_load_string($postdata);
$first = $xml->first;
$last = $xml->last;
$email = $xml->email;
$phone = $xml->phone;
// do your db stuff
// format response
$response = '<response>
<success>Hello World</success>
</response>';
// set header
header('Content-type: text/xml');
// echo xml identifier and response back
echo chr(60).chr(63).'xml version="1.0" encoding="utf-8" '.chr(63).chr(62);
echo $response;
exit;
?>
You should see the response returned from curl_exec()

Related

Api response not showing with curl in php

I want to fetch Api response (created in nodejs) in website using Php,So for this i am using
curl but its not working,I tried with following code but not working for me (showing blank page),Where i am wrong ? Here is my code
$post = ['email'=> "example#xyz.com",'password'=> "testing"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://35.154.149.228:8000/api/admin/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
print_R($result);
Change
$result = json_decode($response);
To
$result = json_decode($response, true);
Then
echo '<pre>';
print_r($result);
Response:-
Array
(
[statusCode] => 401
[error] => Unauthorized
[message] => Invalid username or password
[responseType] => INVALID_USER_PASS
)
change your post array
$post = array('email'=> "example#xyz.com",'password'=> "testing");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://35.154.149.228:8000/api/admin/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
print_r($result);
Try displaying errors just in case the errors/warnings are suppressed.
use these at the top of the file, just after the php tags
ini_set("display_errors", "On");
error_reporting(E_ALL);
Also try to print the raw response before json_decoding it, this is because if the response you are getting is not valid json nothing would be printed out after decoding it.
Use this
print_r("The response is: " . $response);
In summarry your code should look like
ini_set("display_errors", "On");
error_reporting(E_ALL);
$post = ['email'=> "example#xyz.com",'password'=> "testing"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://35.154.149.228:8000/api/admin/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
//Printing the original response before trying to decode it
//$result = json_decode($response);
print_r("The response from the server before decoding is: " . $response);
Let us know what the exact response you get from this is

I have created an call back API to receive the JSON data but its not working

I have created a call back API to receive the JSON data after hitting my server. But somehow its not working as expected
This the response which i have to receive in my API
{"ERROR":0,"STATUS":1,"ORDERID":753093,"OPTRANSID":"2107938600"}
I have written the php file for this rcstatus.php
$url = 'http://softwarecompany.club/pks/recharge/b2b/rcstatus.php?status='.$_GET['status'].'&Orderid='.$_GET['Orderid'].'&Optransid='.$_GET['Optransid'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 30000);
$data = curl_exec($ch);
echo $data;
$json = json_decode($url,true);
$json['STATUS'];
Please help me to achieve this. I have never worked with JSON data before. So please help me to achieve it. Thanks in advance!!!
You need to replace:
$json = json_decode($url,true);
with
$json = json_decode($data,true);
Replace $url to $data in last when you get the response like this.
$url = 'http://softwarecompany.club/pks/recharge/b2b/rcstatus.php?status='.$_GET['status'].'&Orderid='.$_GET['Orderid'].'&Optransid='.$_GET['Optransid'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 30000);
$data = curl_exec($ch); // This is Your Response
$json = json_decode($data,true);
$json['STATUS'];

Process request of cURL

I made a cURL request code and i'd like to process the data it sends.
cURL code:
$url = "http://rbvconsultancy.com/api/post.php";
$xml_builder = '<?xml version = "1.0" ?>
<request>
<no>1</no><dat>hello</dat>
</request>';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_builder);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 28);
$ch_result = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$rest = $ch_result;
echo $rest;
process cURL:
echo "hello".$_GET['para1'];
Based on the code above, i'd like my process cURL code to get the value of $xml_builder. Any ideas on how to do it? It seems that $_GET['para1'] doesnt do the job.
I guess you want this :
you can copy this to your response PHP file
echo file_get_contents("php://input");
Maybe this will help you

Read xml data from url using curl and php

I want to read XML data from a URL. I have the URL as follows:
http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A
Here is my code:
$Url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $Url);
$output = curl_exec($ch);
$resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL resource, and free system resources
curl_close($ch);
Could anyone please tell me how to read xml data?
Here is some sample code (XML parsing module may not be available on your PHP installation):
<?php
$url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url); // get the url contents
$data = curl_exec($ch); // execute curl request
curl_close($ch);
$xml = simplexml_load_string($data);
print_r($xml);
?>
The variable $xml now is a multi-dimensional key value array and you should easily be able to figure out how to get the elements from there.
// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));
// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
This is the demo of how to get channel id from rss feed of youtube in which i read xml data from url using curl.
$channel_id = 'XXXXXXXX'; // put the channel id here
//using curl
$url = 'https://www.youtube.com/feeds/videos.xml?channel_id='.$channel_id.'&orderby=published';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$response = curl_exec($ch);
curl_close($ch);
$response=simplexml_load_string($response);
$json = json_encode($response);
$youtube= json_decode($json, true);
$count = 0;
if(isset($youtube['entry']['0']) && $youtube['entry']['0']!=array())
{
foreach ($youtube['entry'] as $k => $v) {
$yt_vids[$count]['id'] = str_replace('http://www.youtube.com/watch?v=', '', $v['link']['#attributes']['href']);
$yt_vids[$count]['title'] = $v['title'];
$count++;
}
}
else
{
$yt_vids[$count]['id']=str_replace('http://www.youtube.com/watch?v=', '', $youtube['entry']['link']['#attributes']['href']);
$yt_vids[$count]['title']=$youtube['title'];
}
echo "<pre>";
print_r($yt_vids);

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