PHPExcel Excel TO HTML $_sheetIndex error - html

. . . .
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

Related

JSON decode failed

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.

Saving data in a JSON file with WordPress AJAX

So I have a wordpress Ajax function that retrieves MySQL data as JSON and logs it. However I want to not directly get the data back on the page where my AJAX function is, but I want to save the data to a JSON file instead, so I can use it for a wider variety of purposes.
Here is my AJAX function:
$.get(
ajax_url,
data,
function(data) { // AJAX callback
fill_json(data);
}// End AJAX callback
);
The fill_json() is a function to echo the JSON data in a table I wrote myself.
Now here is what happens inside my AJAX hook:
$sql_search = $wpdb->get_results(" a complicated mysql search here ");
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
underneath echo $result; in my Ajax hook I tried the following piece of code, but I don't know how I can see if it worked or not:
$json_path = "/var/www/vhosts/jtc.ae/httpdocs/pre/wp/wp-content/themes/Amazing_japan_HP/new/search.json";
file_put_contents($json_path, $result);
My question:
Is this the correct way to save the data to a JSON file, and how can I get this data on my main page then?
Extra question: Will saving $result to a JSON file conflict with multiple users using the AJAX at the same time?
All you did is right .. please make sure the steps below :
Pass write permission to the folder /new inside "Amazing_japan_HP" (chmod -R 666 /new)
To save the data in file use file_put_contents($file, $current);
To get the data from the file use $current = file_get_contents($file);
For all newly created files try to use umask. It provides required permission to the files for writing content in it
umask() sets PHP's umask to mask & 0777 and returns the old umask.
When PHP is being used as a server module, the umask is restored when
each request is finished.

Converting a JSON output into an end-user readable format

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.

Jsonp proxy Exampple, send request to our own site instead of sencha site

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

return json data from mysql into angular file - works from a text file, but not from php

Very new to angular - just exploring at the moment. Would be very grateful for a pointer or two as to where I am going wring here - TIA
What I would like to do is take data from a mysql select query and return it into an html page, using json and then have angular to display it.
Have succeeded in returning the data using JSON_encode - ran it through jsonlint and it has come back as fine. For testing, I then took this string and created a text file, and ran it through the angular file - it works fine.
If I call the data direct from the php file it fails, but if I call the data from a static text file (with what appears to be the same output as the php data) it works.
I am sending the data with echo - is this correct?
$json=json_encode($main_arr);
echo $json;
json output:
[{"custcode":"CMZIG001","cli":"0020\/1"},{"custcode":"CMZIG002","cli":"0020\/2"},{"custcode":"CMZIG003","cli":"0020\/3"},{"custcode":"999","cli":"002871365801"},{"custcode":"CMSLE001","cli":"0030"},{"custcode":"CMNIC001","cli":"0034"},{"custcode":"CMLIF001","cli":"0047"},{"custcode":"CMTON01101","cli":"0087\/1"},{"custcode":"CMTON01102","cli":"0087\/2"},{"custcode":"CMTRE001","cli":"0090"}]
Text file contents:
[{"custcode":"CMZIG001","cli":"0020\/1"},{"custcode":"CMZIG002","cli":"0020\/2"},{"custcode":"CMZIG003","cli":"0020\/3"},{"custcode":"999","cli":"002871365801"},{"custcode":"CMSLE001","cli":"0030"},{"custcode":"CMNIC001","cli":"0034"},{"custcode":"CMLIF001","cli":"0047"},{"custcode":"CMTON01101","cli":"0087\/1"},{"custcode":"CMTON01102","cli":"0087\/2"},{"custcode":"CMTRE001","cli":"0090"}]
In response to comments:
OK - I had hoped not to bore you with my code. An html file as below (I will try to format it correctly)
<!doctype html>
<html ng-app="App">
<head>
<meta charset="utf-8">
<title>CLIs http</title>
<link rel="stylesheet" href="style.css">
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js">
</script>
<script src="app.js"></script>
</head>
<body ng-controller="TodoCtrl">
<ul>
<li ng-repeat="cli in cli">
{{cli.custcode}} - <em>{{cli.cli}}</em>
</li>
</ul>
</body>
</html>
app.js - currently set to call a php file on my server
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope, $http) {
$http.get('http://localhost/t5/clis.json')
//$http.get('njs.json')
.then(function(res){
$scope.cli = res.data;
});
});
clis.json (the php file on my server)
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db='mutuxf';
mysql_select_db($db, $con);
$result = mysql_query("SELECT custcode, cli FROM clis limit 10");
while($row = mysql_fetch_assoc($result))
{
foreach($row as $key => $value)
{ $arr[$key] = $value; }
$main_arr[] = $arr;
}
$json=json_encode($main_arr);
echo $json;
?>
When I use the php file to raise the data, I merely get a bulleted list with no text, but when I use the text file (njs.json) the page works correctly.
firstly, i would recommend switching from .then() to .success() and .error(), so you know if all is going well.
other than that, since the question information is lacking and quite general, i would bet that the json fetching and building part on the server is the problem.
maybe this link would help
the way they fetch it:
$data = file_get_contents("php://input");
$objData = json_decode($data);
pay attention to the comment, it might be key here:
// The request is a JSON request.
// We must read the input.
// $_POST or $_GET will not work!
in general- if you have the option to add or switch framework on the backend, i would recommend symfony/django for php or switch to RoR with RABL/GON to generate the jsons. it's so much easier and intuitive.
hope it helps, it's been a while since i used vanilla php.
It's becauce you can not run php in a .json file, clis.json needs to be clis.php or you can have the php script write to a separate json file, which would hold the data