At current, I am trying to build a license script that calls my licensing API. When a call is made, a JSON output is returned. For example:-
{"result":null,"error":{"message":"Error explanation","code":101}}
Is there a way that I can convert this into a readable format via PHP so that it looks something like:-
License Error: *Error Message Here* (Error Code: *Error Code Here*)
as if I was able to do the following:
<?PHP
echo $errorMessage; // Show's the "Error explanation" message.
?>
Thanks
http://php.net/manual/en/function.json-decode.php
did you try googling anything?
$json = '{"result":null,"error":{"message":"Error explanation","code":101}}';
$obj = json_decode($json);
print $obj->result; // null
I'm not that familiar with PHP output on JSON, but I imagine something like:
print $obj->error->message //Error explanation
print $obj->error->code //101
I am not sure about the exact PHP syntax but that's basically how it works.
Related
Following is the code snippet where I am observing error: "malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)") at"
Error observed is at the decode_json line. Can someone point out what is the error?
my $serverurl = "http://mycompany.net/rest/api/2/";
my $username = 'my.email#domain.com';
my $password = "mypassword\#2019";
my $i ;
my $test;
my $headers = {Accept => 'application/json', Authorization => 'Basic ' .encode_base64($username . ':' . $password)};
my $client = REST::Client->new();
my $idartinstance;
my $idartinstance1;
if (!$idartinstance)
{
print " Trying to Connect to URL using REST client interface \n\n";
$idartinstance1 = $client->GET($serverurl."serverinfo",$headers);
$idartinstance = decode_json($idartinstance1->responseContent());
}
When I print $idartinstance, I get this:
REST::Client=HASH(0x8682024)->responseContent()
Does this mean, it is not able to find REST client?
[EDIT] I have modified the script as below and no difference in the errors.
my $serverurl = "https://mycompany.net/rest/api/3/";
my $username = 'my.email#domain.com';
my $password = 'pf9fCdkGXmi4pMHiwIh74A0D';
my $headers = {Accept => 'application/json', Authorization => 'Basic ' . encode_base64($username . ':' . $password)};
my $client = REST::Client->new();
if (!$idartinstance)
{
print " Trying to Connect to JIRA using REST client interface \n\n";
$client->GET($serverurl."serverInfo", $headers);
print $client->responseContent();
$idartinstance = decode_json($client->responseContent());
}
Now I have used encoded password. Error is same: malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)"). Tried accessing "https://mycompany.net/rest/api/3/serverInfo" via web browser and able to get the details.
Once you get a response, you have to check that its what you want.
if( $client->responseCode() eq '200' ){
print "Success\n";
}
You may also want to check that the content-type is what you expect. If it's supposed to be JSON, check that it is:
if( $client->responseHeader('Content-Type') =~ m|\Aapplication/json\b| ) {
print "Got JSON\n";
}
Once you've established that you have what you wanted, pass the message body off to the JSON decoder.
my $data = decode_json($client->responseContent());
You might also try to catch errors where you should have valid JSON but don't. The block eval can handle that (and see the many sources of the proper employment of eval for its best use):
my $data = eval { decode_json(...) };
I find that I tend to get the wrong content in two situations:
the wrong endpoint, from which a 404 handler returns HTML
a captive portal, which also returns HTML
I think you're misreading the documentation for the module. From the synopsis there, the example that most closely resembles yours is the first one:
my $client = REST::Client->new();
$client->GET('http://example.com/dir/file.xml');
print $client->responseContent();
Notice, in particular, that this example does nothing with the return value from GET(). In your example you do the equivalent of this:
my $client = REST::Client->new();
my $resp = $client->GET('http://example.com/dir/file.xml');
print $resp->responseContent();
As it happens, although there is no documented return value from GET() [Update: I was wrong here - see the first comment - but the return value is really only intended for chaining method calls], it actually returns the object that it was passed, so your approach should work. But it's generally a bad idea to not follow the documentation.
So what is actually going wrong? Well, I'm not sure. As I said, your approach should (accidentally) work. But the error message you're getting tells us that what you're passing to decode_json() is a REST::Client object, not a string containing JSON. I don't think that's how your code should work. Perhaps the code you've shown us isn't actually the code you're running.
The best approach to debug this is to follow the advice from Quentin in the first comment on your question - print the value that you're trying to pass to decode_json() before passing it to the function. In fact, that's good general programming advice - originally write out your code step by step, and only combine steps once you know that the individual steps are working correctly.
Using your variable names, I think your code should look like this:
my $client = REST::Client->new();
# ...other code...
$client->GET($serverurl."serverinfo", $headers);
print $client->responseContent();
# And, only once you've established that
# $client->responseContent() returns what
# you expect, you can add this:
$idartinstance = decode_json($client->responseContent());
If the print() statement doesn't show you JSON, then update your question to add whatever is printed and we'll take a further look.
I'm actually scripting and a part of my script is a FTP file download. The code words without any problem, but I don't understand one specific part. Its the only part from the code I haven't written by myself. I understand how the code works, but I actually dont understand how the function return its value. You're may confused what I mean, so let me explain it with a bit of code:
function get-ftp {
try {
$ftprequest = [system.net.ftpwebrequest]::Create($uri)
$ftprequest.Credentials = New-Object system.net.networkcredential($user,$pass)
$ftprequest.Proxy = $null
$ftprequest.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
$ftpresponse = $ftprequest.GetResponse()
$reader = New-Object IO.StreamReader $ftpresponse.GetResponseStream()
$reader.ReadToEnd()
$reader.Close()
$ftpresponse.Close()
}
catch {
Write-host "Error while reading filenames"
}
}
So this is my function to get all directories from the FTP server. I call this function with this code:
$allXmlFiles = get-ftp
So after the call, my $allXmlFiles contains a string (tested with getType on $allXmlFiles) with all the filenames on the server. Now my question: How is the answer from the FTP passed to this variable? There's no return in the function, so I'm quite confused how this works. I tried so take the try/catch out of the function and access the answer directly, but that didin't work. I tried to find it in $reader and in $ftpresponse - no success.
It would be really cool if someone can explain me whats going on here. As said, the code works, but I would like to understand whats going on here.
It's
$reader.ReadToEnd()
StreamReader.ReadToEnd() method outputs string and since it's result is not assigned to variable it will be the function output.
Idiomatic way would be to write it like this:
Write-Output $reader.ReadToEnd()
In PowerShell, the result of every command / statement is returned as output if you don't assign or pipe it to anything.
The return keyword only exits the current scope. You rarely use return in PowerShell.
As beatcracker mentioned, $reader.ReadToEnd() is producing the output.
. . . .
I am using Codeigniter 3.1 and PHPExcel 1.8.
I have a function that creates a PHPExcel Object and returns it and the other function outputs the Excel to browser
$objPHPExcel = $this->MyExcelModel->my_function();
$file_name = "my_file.xls";
Content-Type: application/vnd.ms-excel");
Content-Disposition: attachment; filename=$file_name");
Cache-Control: max-age=0");
PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel5");
save("php://output");
This is working perfectly fine. Now I also need the HTML of the same Excel Data. Previously I am creating a separate preview function. But whenever there is a chnage I have to do it in two locations. So I searched and found that I can generate HTML too using PHPExcel. Following is the code that I used
$objPHPExcel = $this->MyExcelModel->my_function();
$objWriter2 = new PHPExcel_Writer_HTML($objPHPExcel);
$html = "";
$html .= $objWriter2->generateHTMLHeader();
$html .= $objWriter2->generateSheetData();
$html .= $objWriter2->generateHTMLFooter();
I am sending this html in json response for an ajax call. When the function is called. I get an error
<h4>A PHP Error was encountered</h4>
<p>Severity: Notice</p>
<p>Message: Undefined property: PHPExcel_Writer_HTML::$_sheetIndex</p>
<p>Filename: Writer/HTML.php</p>
<p>Line Number: 401</p>
and the json response has the html too. So the html is generating but I am getting this error. I have searched a lot but without success. So I have pretty much got what I needed but this error is restricting me from using it. so HELP . . . . .
Go and edit /Classes/PHPExcel/Writer/HTML.php and find line 401, which reads
if ($this->_sheetIndex !== null || !$this->spansAreCalculated) {
change it to read
if ($this->sheetIndex !== null || !$this->spansAreCalculated) {
To fix it immediately
I'll push the fix to the develop branch on github in a few minutes
I'm designing a jsonp example where I want to make a call to some different domain, so I'm making a call to http://www.walkingtree.in/forums/topics-browse-remote.php, instead of http://www.sencha.com/forum/topics-browse-remote.php.
The data is printing same format in both the case, but while executing am getting some error in console
Uncaught SyntaxError: Unexpected token : topics-browse-remote.php:1,
but there is no such error.
When I am watching the response there is only one change in response i.e when I'm making call to sencha forum then the response is coming inside Ext.data.JsonP.callback1({......})
and in the other forum case its coming simply like this {.............}
Any help is highly appreciated
I got the solution. The problem was there in the php file. Inthis type of request generally one queryString will go with callback, so we need to get the callback and append it to our response so that response will come properly.
Sample php code :
<? php
$callback = $_REQUEST['callback'];
$output = array('a'=>'any text', 'b'=>'some other Text');
if ($callback) {
header('Content-Type: text/javascript');
echo $callback . '(' . json_encode($output) . ');';
} else {
header('Content-Type: application/x-json');
echo json_encode($output);
}
?>
Thanks
Tapaswini
I have a script on one server which is posting a json array to another server which is not decoding it. I printed the POST and see that it's receiving it correctly but then it's not able to decode it. This is what I tested with, it prints the sent json array but isn't decoding it.
print_r($_POST);
$inputArray = json_decode($_POST['inputarray'], TRUE);
echo "<pre>";
print_r($inputArray);
Is your data json encoded, if yes then check for errors, try:
$json = json_encode($text);
$error = json_last_error();
var_dump($json, $error);
Got it working by stripping slashes. On my local server it was working but not the remote server which was strange. Found out this works.
$inputstring = stripslashes($_POST['inputarray']);
$inputArray = json_decode($inputstring, TRUE);