Rendering JSON with Cakephp - php

I'm trying to return a Json object from an outside form with Cakephp 2.1. I have all my data, and I've looked at the responses, and the problem is I get a massive error text before my JSON!
Heres the code I use to print the json:
if (!$validationPassed) {
if ($ExternalRequest) {
if ($shouldEchoErrors){
Configure::write('debug',0); // Disabled so theoretically it can't even print errors
$this->RequestHandler->setContent('json', 'application/json' );
$json = json_encode($this->Customer->validationErrors);
echo $json;
$this->autoRender = false ;
}
The JSON it prints is correct, {"Email":["EmailUnique"]}. However I get a huge preformatted error message before that, stack trace and everything.

It was a dumb moment, but the answer in case anyone else finds this:
Theres an error far earlier in the code, with debug on, cake will print it immediately. This will get wrapped into the json output.
The specific error turns out to not be relevant for this question, its just in the view.

Related

Trying to get property of non-object with syntax error

I created a instagram feed for opencart and when i wrote the code in normal php file it worked perfectly but when i transformed to opencart controller view it returns when
json_last_error();
int(4) syntax error
and here is my code in controller
$response= utf8_encode(file_get_contents("https://www.instagram.com/user/?__a=1"));
$response= str_replace(array('ï',''), '',$response);
$response= json_decode($response);
$data['orgimages'] = json_last_error();
i tried so many solutions or filtering out methods and that is my final code as it was changed so many times from stackoverflow answer solution for other questions but nothing seems to be worked out and even their forums didn't worked out with my issue.
Your error indicates that your json is wrongly formatted so try to echo it and validate it. I am suspecting that your json is not a valid json.
Use this : https://jsonlint.com/ validator for json.
After this line :
$response= str_replace(array('ï',''), '',$response);
echo your $response variable and see how your json looks like

rest echo vs return in GET

I am a newbie in php and rest and I'm trying to understand what is going on in my API when using echo vs return....
I've tried to get down to the simplest possible scenario to isolate an issue of my rest API not returning any value, so here is goes:
I have a test.php file on my server with following content:
<?php
if(function_exists($_GET['t1'])) {
echo $_GET['t1']();
}
else if(function_exists($_GET['t2'])) {
return $_GET['t2']();
}
function test() {
return json_encode("test...");
}
?>
I then make a simple request using, as unique header 'Content-Type: application/json`
https://www.eswys.ch/tmp/test.php?t1=test
https://www.eswys.ch/tmp/test.php?t2=test
And results are, respectively
"test..."
""
I really struggle to understand this, why is my returned value somehow "lost" - is there any explanation to this?!
Returning from a function does not actually render any content to the response. You may have seen people returning data in different frameworks but the framework is actually echoing the data for you behind the scenes.
return assigns a value to a function call (like a variable) and echo is simply output to the html page or possibly a terminal window.

PHP Error handler triggers when using die in outputbuffer context

im developing my PHP framework and at the moment im stuck with a strange behaviour in my error-dispatching page.
The page itself is beautiful, it catches and lists all error using a custom error-handler registered with "set_error_handler()" and can print the line, file, invoked variables and such. It even triggers multiple errors perfectly (except for fatal or syntax-errors which causes the script to hold) but still the dispatches the fatal or even syntax error in this case and even shows me, even when its a null-pointer in a template where the error is located which is beautiful and works awesome.
This system works "using set_error_handler"! The entire output (rendering html /php templates) is realised using "ob_start" and "ob_get_clean" - outputbuffer context.
Next I check if the error-handler catched any errors (will be written in an array in the error-handler's class) and if there are errors and error-display is enabled (developer mode = on) the error-dispatcher page will be displayed instead of the page's content.
However since I implemented that I have one strange behaviour which I do not want:
Whenever I use die() inside of outputbuffer context ((ob_start() ... ob_get_clean()) ) The registered error-handler method is called with an empty error-list displayed and even error_get_last() is empty, but still he triggers that damn function.
This is very disturbing as you cant use die to hold the script to test the output of certain variables which is disturbing in development and seems to be an unusual behaviour to me.
I think posting my entire code is making the thing a little bit too complicated for you to understand thatswhy I leave a little draft explaining the situation, its basically same as it looks in my classes:
//index.php
$errorList = array();
function myErrorHandler($errorType, $errorString, $errorFile, $errorLine, array $errorContext) {
global $errorList;
$errorList[] = $errorString;
}
set_error_handler("myErrorHandler");
//Here my classses and entire rest of framework is loaded...()
//Initialise output
$output = "";
//This method parses templates, it remotely close works like that...
function includeTemplate($templatePath) {
global $output;
ob_start("myErrorHandler");
include($templatePath);
$output .= ob_get_clean(); //Attach to output
}
//This method is called at the very end, it flushes the output, wether by displaying error-dispatcher or page content to be shown.
function flush() {
global $output;
if(count($errorList) > 0) {
echo implode("<br />", $errorList);
} else {
echo $output;
}
}
//Template file: registerTemplate.php
<div class="container">
<Some template output here, doesnt matter if an error occured...>
<?php die($var); ?> //<- Error rised -> Entering "myErrorHandler()" -> but why????
</div>
-> This die() above would rise an error because registerTemplate.php was somewhen parsed using includeTemplate("reigsterTemplate"); which is as located within an ob_start() context. It does not matter if an error occured before or not or even if I just place die("!"); without any invoked variable, it will riase an error.
If I put the die() before or after the include_template context, in upper scope it works as usual and the error_handler does not trigger, as it should work.
Can anyone tell me why this is happening? Thanks alot!
(Important: again this code is not realistic I know its just a draft from how the things look like very barely, dont bother with that giving me hints that this is a bad way to do things. The entire thing is perfectly object oriented and very well structured. I just made this little draft to make you guys understand in what order the methods are called and how my problem comes up because posting my code would waste me and you alot of time as it would be too huge and complex here).

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 catch error in JSON response?

I'm getting the json data from the twitter using the wordpress function wp_remote_get as below:
$response = wp_remote_get('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitter');
$json = json_decode($response['body']);
and it works fine. However, it totally creates the problem on my page if the twitter returns some error. In that case the content on my page does not load after that error part. So how can I catch the error and continue, only if there is no error.
For example if the twitter limit exceeds, it returns following response:
{"request":"\/1\/statuses\/user_timeline.json?screen_name=twitter","error":"Rate limit exceeded. Clients may not make more than 150 requests per hour."}
From the above responsive, how can i get the error.
I'm trying following, but it does not work (my page does not load at all)
if (!isset($json['error']){
//continue
}
It doesn't work because you are trying to access $json as an array, which it is not. It's an object, so use:
if (!isset($json->error){
//continue
}
Your page doesn't load because it's causing a fatal error, which in turn produces a 500 internal server error. If you check your error log you'll find:
Fatal error: Cannot use object of type stdClass as array in ....
You need to use json_decode to "transform" your "json string" in an object.
$j = json_decode($json);
echo $j->{'error'}
Here you will find everything what you need to know about json_decode: http://php.net/manual/en/function.json-decode.php

Categories