How to return a response via php - php

I'm writing a php api with methods wired together by php routing, such that
dev.myphp.com/user/login?email=sdfsdf#fdfd.com&password=d514
will return a json/xml response.
However, I do not know how to return this response, even if I use json_encode or xml_encode to conver the data string.
Do I just need to uniquely echo the JSON string out?

Always try to take data using POST method not GET , untill unless you don't find it less useful in caompare to POSt.
use simply
<?Php
--- php code
return json_encode($resultdata);
?>
it would be enough.

Related

Get PHP response into Zapier webhook

I am connecting PipeDrive with Post Affiliate Pro (with it's API) and am using Zapier webhooks (POST). Therefore I use PHP scripts on my server in which I talk to Post Affiliate Pro. So I have variables in my PHP script which I need to return in order to use them in another webhook/or general action step. In Zapier the only variable I get when testing the step is a String with my response message (and whatever variable I put in there). But I need to get all variables on their own (I guess all in a JSON).
So my question is: How can I return variables in an HTTP POST request to make them available (in the dropdown list?) in Zapier to use them in the next webhook?
At the moment I have something like this:
if ($result->isError()) {
echo 'Error: '.$result->getErrorMessage();
} else {
//echo 'Ok: '.$result->getInfoMessage();
echo json_encode($orderID);
I am using 'echo' but I've also tried to use 'return' which didn't lead to any results. I've also tried to use json_encode to return a JSON but without luck. Or do I even need to use another Zapier step? Or am I not able to return values with a POST webhook at all? Do I need to use a "Catch Hook" webhook? I am completely new to Zapier and PHP.
Image shows just two Strings ('Text' & 'Text Transaktion') available in Zapier but no other variables
Thanks for your help!
I finally found it out by myself. I have to return one JSON, which includes everything. It's also not possible to echo anything at the same time as this would result in the output of just one string with all the values in it (like I had it before).
So something like this does the job:
if (!isset($returnValue)) {
$returnValue = new stdClass();
$returnValue->order_id = $orderID;
$returnValue->result_message = $resultMessage;
}
print_r(json_encode($returnValue));

PHP json_encode on a SOAP response returns array if multiple, but object if single?

I have a Windows Desktop Gadget that, for a small number of my users, suddenly stopped working a few months back. Seemed to be that they suddenly didn't like cross-domain requests (even though all servers are on our intranet here). So, I'm rewriting the thing so that it goes to a single backend server that I have a lot of control over... and its Ajax queries to the backend are set to use data Type: jsonp. Meanwhile, the php script that the gadget queries a la Ajax calls a SOAP service, gets the data back, turns it into an array, and then uses json_encode to turn it into a string and add a reference to a callback function on the Gadget / javascript side.
My problem seems to be with json_encode. If the SOAP response includes a single data record, it sends it as an object. If the SOAP response contains multiple records, it's slapping brackets around it, like an array.
Examples:
Single record:
`{
"SmeDetail": {
"SipAddress": "jane.smith#whatever.com",
"SubjectExpert": "Smith,Jane",
"SubjectMatter": "Unix"
}
}`
Multiple records:
`{
"SmeDetail": [
{
"SipAddress": "fred.flintstone#whatever.com",
"SubjectExpert": "Flintstone,Fred",
"SubjectMatter": "Bedrock"
},
{
"SipAddress": "barney.rubble#whatever.com",
"SubjectExpert": "Rubble,Barney",
"SubjectMatter": "Bedrock"
},
{
"SipAddress": "wilma.flintstone#whatever.com",
"SubjectExpert": "Flintsone,Wilma",
"SubjectMatter": "Bedrock"
}
]
}`
In the php script, a typical SOAP call goes like this:
$Service_URL = 'http://server/PROD/OurWcfService/WcfService.svc?wsdl';
$client = new SoapClient($Service_URL);
$res= $client->GetSMEDetails($params)->GetSMEDetailsResult;
and then $res is fed to this routine:
$json_data = json_encode((array)$res);
echo $_GET['callback_name'].'('.$json_data.');';
And that echo is what's fed back as the Ajax response.
I'm not sure where I even read about using this json_encode((array)$res) to do the conversion from the Soap response into an array, then the json encoded string. But I'm wondering if I'm doing something wrong here? I guess I need to make sure that single records are pushed through as an array. And I'd rather fix that the "right way" rather than do some sort of hack on the string.
Any thoughts?
I think the problem occurs cause GetSMEDetailsResult returns not array(singlerecord) but singlerecord itself.
What about checking "is SmeDetail associative"?
hint: How to check if PHP array is associative or sequential?
function isAssoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($res['SmeDetail'])) $res['SmeDetail'] = array($res['SmeDetail']);
This solution is ugly but it should work.
Another way is to check "is SipAddress set":
if(isset($res['SmeDetail']['SipAddress'])) $res['SmeDetail'] = array($res['SmeDetail']);

How to get an array instead of object when requesting JSON data using HTTPful

I'm using HTTPful to send some requests in PHP and get data in JSON, but the library is converting the result into objects, where I want the result to be an array. In other words, its doing a json_decode($data) rather than json_decode($data, true).
There is, somewhere, an option to use the latter, but I can't figure out where. The option was added in v0.2.2:
- FEATURE Add support for parsing JSON responses as associative arrays instead of objects
But I've been reading documentation and even the source, and I don't see the option anywhere... The only way I can think of is making my own MimeHandlerAdapter which does a json_decode($data, true) but it seems like a pretty backwards way of doing it if there is an option somewhere...
It may be a little late to answer this, but I did a little research while using Httpful and found the answer. Httpful uses a default set of handlers for each mime type. If one is registered before you send the request, it will use the one you registered. Conveniently, there is an Httpful\Handlers\JsonHandler class. The constructor takes an array of arguments. The only one it uses is $decode_as_array. Therefore, you can make it return an array like this:
// Create the handler
$json_handler = new Httpful\Handlers\JsonHandler(array('decode_as_array' => true));
// Register it with Httpful
Httpful\Httpful::register('application/json', $json_handler);
// Send the request
$response = Request::get('some-url')->send();
UPDATE
I realized that it sometimes parses the response into a funky array if you don't tell the request to expect JSON. The docs say it's supposed to work automagically, but I was having some issues with it. Therefore, if you get weird output, try explicitly telling the request to expect JSON like so:
$response = Request::get('some/awesome/url')
->expects('application/json')
->send();
I never used this library. But in a research I found that you can find this option at src/Httpful/Handlers/JsonHandler.php on line 11.
There you will see:
private $decode_as_array = false;
And this flag is used at the same file on line 27:
$parsed = json_decode($body, $this->decode_as_array);
You have to set decode_as_array to true value, to do this:
\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true)));
before Request::get calling

angular js with php integration

I used the code from http://angularjs.org/ (Wire up a Backend)
Here in project.js
angular.module('project', ['firebase']).
value('fbURL', 'https://angularjs-projects.firebaseio.com/').
factory('Projects', function(angularFireCollection, fbURL) {
return angularFireCollection(fbURL);
}).
config(function($routeProvider) {
I used this code in my web page. Instead of https://angularjs-projects.firebaseio.com/ url i want to use my url i.e http://test.com/test.php. But it didn't work.
Also i want to know in my php file in which format the out put should be?
Do you need to echo the content in php file or use the return command? Please give suggestion. I have searched a lot. I couldn't find the solution.
I think in firebase url https://angularjs-projects.firebaseio.com/ they are returning the response from their back-end service. That is why it didn't worked for you even if you changed the URL.
And answer to your second question;
If you make a call to your back-end service its better to have a json response style from your PHP and you don't have to use any return command for that. Instead you should echo your contents.
For example in your PHP file if you are getting the results as an array you can give back the response to the angular application as;
echo json_encode($result_array);
Hope it helps.
I think you should separate backend and frontend and treat them as two separated application. Both apps should communicate with each other by sending ajax request (front) and respone data in json format (backend). In my opinion it's the best way to handle this.

How do I use external JSON...?

spent a few hours trying to figure this out, but cannot for the life of me figure out what's going wrong.
All I'm trying to do is load this:
https://recruit.zoho.com/ats/EmbedResult.hr?jodigest=2cV.Sr2As6VxhLMxQGuTNij*g.Fb3J7ysduDs.AC9sU-&atslocale=en_GB&rawdata=json
which I believe is json, into either javascript/jquery or php and use the data.
I've looked into jsonp, followed some tutorials, used some demos as templates and just can't get the above data to work.
If anyone can shed some light it would be much appreciated. It really shouldn't be this complicated, but I don't know what's going wrong.
Yep, that's JSON. The site may not support JSONP, so you're gonna have to use PHP to do this.
This is untested, but should work.
<?php
$url = 'https://recruit.zoho.com/ats/EmbedResult.hr?jodigest=2cV.Sr2As6VxhLMxQGuTNij*g.Fb3J7ysduDs.AC9sU-&atslocale=en_GB&rawdata=json';
$JSON = file_get_contents($url);
// echo the JSON (you can echo this to JavaScript to use it there)
echo $JSON;
// You can decode it to process it in PHP
$data = json_decode($JSON);
var_dump($data);
?>
JSONP relies on the server to return a JSONP formatted response. Basically, to use JSONP the server needs to return a JSON string wrapped in a function invocation ({"foo":1} becomes func({"foo":1})).
As the server your using doesn't return a JSONP response, you cannot use JSONP, you can only use JSON.
This is a shame, as JSON cannot be used x-domain due to the same origin policy (SOP). Therefore, the only option you have is to use a proxy server, which retrieves the JSON from the server, and either gives it to you in JSONP (see Yahoo Pipes), or which is on the same domain as the requested page (write a simple PHP script to get the file using file_get_contents() and then echo the output), in which case it can return the JSON.
I breifly looked at the requirements and it looks like you need an API key as well as an account. I saw that the site provides services for XML and JSON only. It looks to be fairly well documented.

Categories