Render XSL file to HTML using PHP - php

I need to read a excel (xls) file and render it to a HTML page.
I'm developing in PHP, using Symfony 2.6.5 and I want to have access to the excel cel data, in this way I can generate HTML in a Symfony Controller(or better in a a Template).
I'm using ExcelBundle and I've read the documentation, but I found only ways to set information and not to get.
Which is the best we to read the content of the excel?
PS: the excel is a price list in a tabular form like the follow:
+––––+––––––+–––––––––––––+–––––––+
| id | name | description | price |
|____|______|_____________|_______|
+––––+––––––+–––––––––––––+–––––––+
| 1 | foo | foo desc | 12€ |
+––––+––––––+–––––––––––––+–––––––+
| 2 | bar | abr desc | 65€ |
+––––+––––––+–––––––––––––+–––––––+
|... |... | ... | ... |

In according with the code source, simply pass the filename in the createPHPExcelObject method.
As Example:
public function xlsAction()
{
$filenames = "your-file-name";
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filenames);
foreach ($phpExcelObject ->getWorksheetIterator() as $worksheet) {
echo 'Worksheet - ' , $worksheet->getTitle();
foreach ($worksheet->getRowIterator() as $row) {
echo ' Row number - ' , $row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
echo ' Cell - ' , $cell->getCoordinate() , ' - ' , $cell->getCalculatedValue();
}
}
}
}
}
Simply pass the array to your view for rendering in the template.
Hope this help

Related

Php voucher system - update codes

I have this voucher system, that works very well. I ust want to change the code to extract vouchers code and value from database.
cart.php Voucher code is :
$cartTotal = 100;
if (isset($_POST['disCode'])) {
$arr = file('flatfile1.txt');
$disCode = strtoupper(trim($_POST['disCode']));
$found = false;
- List item
foreach($arr as $str)
{
// Skip empty or invalid lines (assuming your file flatfile1.txt has blank lines).
if (strpos($str, '|') === false)
continue;
list($code,$amount,$valz) = explode('|',$str);
if ($disCode === trim($code))
{
// Code found.
$cartTotal = round($cartTotal/$amount );
$found = true;
break;
}
}
if (!$found)
$mesaj_eroare= "sorry,voucher code: $disCode is not good";
else
$mesaj_aplicare_voucher = "succes message here.";
}
And flatfile1.txt has :
TEST20% | 1.20 | 20%
TEST10% | 1.1 | 10%
TEST05% | 1.05 | 5%
test20% is the voucher code, 1.20 is the value of code, and 20% is for a custom message to apear to the user.
I tried to change flatfile1.txt to flatfile1.php where i retrive values from database.
Database have this format
TEST20% | 1.20 | 20%
TEST10% | 1.1 | 10%
TEST05% | 1.05 | 5%
And values are recognised in flatfile1.php but when i tried to apply them into cart.php to the voucher system are not recognised.
Need a solution to replace flatfile1.txt to flatfile1.php for automatization of vouchers.

Passing String Arrays into PHP file with Android

I'm trying to use retrofit and PHP to store values in MySQL. I will pass in to the PHP a single postid string (postid) and a string array. For each index in the string array (called tags) I will make a unique row in the database. It will have the following form:
--------------------
|postid | tags |
--------------------
| postid | tags[0]|
| postid | tags[1]|
| postid | tags[2]|
....................
--------------------
The issue I am having is that for the string array, only the last value in the array is being stored.
Here is the retrofit interface
#FormUrlEncoded
#POST("create_recipe.php")
Call<Void> createRecipe(
#Field("postid") String postid,
#Field("tags") String[] tags
);
and the retrofit client call
Retrofit retrofit = ApiClient.getClient();
ApiInterface apiService = retrofit.create(ApiInterface.class);
Call<Void> call = apiService.createRecipe(postid, tags);
call.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
}
});
Here is what the PHP that handles this looks like (excluding some of the init code)
if (isset($_POST['postid']) && isset($_POST['tags']){
$uid = $_POST['postid'];
$tags = array($_POST['tags']);
$tags_new = str_replace(array('[', ',', ']'), '' , $tags);
foreach ($tags_new as $value){
mysql_query("INSERT INTO Tags(postid, tag) VALUES('$postid', '$value')");
}
}
If I pass in postid = 30 and tags = {"milk", "cheese", "bread"} I want it to look like
--------------------
|postid | tags |
--------------------
| 30 | milk |
| 30 | cheese |
| 30 | bread |
....................
--------------------
but instead only bread will be stored.
How do I handle the string array passed in as a parameter in PHP?
What is the form of the array when I pass it onto $tags?
I had the same problem some time back and found no clear solution for it. However I built a simple solution for something similar. I hope this solution helps.
Actually, you can print it out in the PHP work sheet, you can add the following to log the input here.
file_put_contents("test.log",json_encode($_POST)."--".json_encode($_GET));
Only then will you be able to determine whether the array is correctly delivered to the php script.
you might want to reconsider about this, because the following line is basically just removing all the barriers in the string($tags, which is now interpreted as a String instead of an array):
$tags_new = str_replace(array('[', ',', ']'), '' , $tags);
and change it into
$tags_new = split(',' , $tags);

php multi dimensional array's

I am pulling data out of a table that has these fields:
zipcode,city,state,county
My question is that some zip codes are in multiple cities, and some cities are in multiple zip codes... so is there a way to have all the data put into an array, then group all of the zip codes in order, then build a table out of that, so that it puts them in order, but if the data is redundant, like the zip, city, state and county are already in the array, then it skips it?
so then I can print it to the browser using echo, into a table like this:
74801 | Shawnee, Oklahoma | Pottawatomie
74801 | Bethel, Oklahoma | Pottawatomie
74801 | Johnson, Oklahoma | Pottawatomie
74851 | McLoud, Oklahoma | Pottawatomie
74851 | Dale, Oklahoma | Pottawatomie
etc.
But in the case of these:
74015 | CATOOSA, Oklahoma | Rogers
74015 | COTOOSA, Oklahoma | Rogers
Because those are duplicates in those fields (not in the rest of the table), I need it to skip showing it twice.
I think it is something like this:
$zipArray = array();
$zipCode = $dbhhandle->zip;
$cityName = $dbhhandle->city;
$countyName = $dbhhandle->county;
if($zipArray[$zipCode][$cityName] != $countyName) {
$zipArray[$zipCode][$cityName] = $countyName;
}
but I'm not sure if that is the right way to do it.
Then once I have the array built, how do I build the table?
Your code looks pretty close, but it's missing the state. So change the elements of the array into associative arrays with state and county elements.
Also, you need to check whether there's an entry for the zip code at all, before checking whether it's a duplicate, otherwise you'll access an undefined index.
$zipArray = array();
$zipCode = $dbhhandle->zip;
$cityName = $dbhhandle->city;
$countyName = $dbhhandle->county;
$stateName = $dbhandle->state;
if(!isset($zipArray[$zipCode][$cityName]) || $zipArray[$zipCode][$cityName]['county'] != $countyName) {
$zipArray[$zipCode][$cityName] = array('county' => $countyName, 'state' => $stateName);
}
To display the table, you use nested loops.
foreach ($zipArray as $zip => $cities) {
foreach ($cities as $city => $cityData) {
echo "<tr><td>$zip</td><td>$city, {$cityData['state']}</td><td>{$cityData['county']}</td></tr>";
}
}

getting child id's from database dynamically?

I try to get the child id's of products dynamically.Below is my table structure.
parent|child
---------------------
44 | 35,6,47,5,50
---------------------
47 | 8,9
---------------------
50 | 12, 15
am going to pass only one parent id and get the child ids, and if anyone of child ids having again child, then i have to fetch that record also.example 44->35,6,47,5,50 in this 47 and 50 is having child ids, so my final output should be like this 44-> 35,6,47,8,9,5,50,12,15.
I tried below this,
$sql=mysql_fetch_assoc(mysql_query("select * from chain_product where parent='44'"));
$parent=$sql['parent'];
$child=$sql['child'];
$ex=explode(",",$child);
$count=sizeof($ex);
for($i=0;$i<$count;$i++)
{
$list=add_child($ex[$i],$child);
$check=explode(",",$list);
$chck_count=sizeof($check);
if($chck_count>$count)
{
$exit=add_child($ex[$i],$list);
print_r($exit);
}
}
function add_child($main,$ch)
{
$find=mysql_query("select * from chain_product where parent='$main'");
$res=mysql_fetch_assoc($find);
if($res)
{
$replace=$main.",".$res['child'];
$alter=str_replace($main,$replace,$ch);
echo $alter;
}
}
but i get the result like this,
35,6,47,8,9,5,5035,6,47,5,50,12,15
but i need output should be like this..
35,6,47,8,9,5,50,12,15.
can anyone help me to do this..
Your database structure isnt optimal for this, this would be better:
id | parent
1 | 0
2 | 1
3 | 1
4 | 2
5 | 2
This way you can do something recursive:
function getChilds($parent=0, $depth=0){
// Select the items for the given $parent
$query = $conn->mysqli_query("SELECT id WHERE parent=".$parent); // mysqli is better, but mysql will do fine
// get the items by the parent giving as input:
while($fetch = $query->fetch_assoc() ){
echo str_repeat('-', $depth) . " ".$fetch['id'];
getChilds($fetch['id'], $depth+1); // Use id of this line to find its childs
echo "<br />";
}
}
getChilds(0); // And start it. The 0 is optional, I personaly prefer -1. Whatever rows your boat
This is called a tree structure and should give something like this:
1
- 2
- - 4
- - 5
- 3
In this example I use an echo for display purposes, you can return the values via an array, same principle
To answer a bit better, your current structure could support a similar method, but because you use strings, it will be allow slower and alot less flexible. You can see the difference in the code you are using, and the amount I just used. If you would remove the echo's and only return arrays, it will be even smaller :)

Parse JSON Freebase results in PHP

I'm really sorry if this is too basic, but I really don't know how to do this.
I'm using this jquery Autocomplete plugin: http://devthought.com/wp-content/projects/jquery/textboxlist/Demo/
EDIT: This is the jquery code i use for the autocomplete:
$(function() {
var t = new $.TextboxList('#form_topick_tags', {unique: true, plugins: {autocomplete: {
minLength: 2,
queryRemote: true,
remote: {url: 'autocomplete2.php'}
}}});
The plugin uses a PHP for autocomplete, this is an example, it returns this output: "id, text, null (html I don't need), some html"
$response = array();
$names = array('Abraham Lincoln', 'Adolf Hitler', 'Agent Smith', 'Agnus', 'Etc');
// make sure they're sorted alphabetically, for binary search tests
sort($names);
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
foreach ($names as $i => $name)
{
if (!preg_match("/^$search/i", $name)) continue;
$filename = str_replace(' ', '', strtolower($name));
$response[] = array($i, $name, null, '<img src="images/'. $filename . (file_exists('images/' . $filename . '.jpg') ? '.jpg' : '.png') .'" /> ' . $name);
}
header('Content-type: application/json');
echo json_encode($response);
I need a similar PHP to process this results: http://www.freebase.com/private/suggest?prefix=beatles&type_strict=any&category=object&all_types=false&start=0&limit=10&callback=
...being "beatles" the $search value, and getting this output:
guid,"name",null,"name<span>n:type name</span>"
So, the first result would be:
0,"The Beatles",null,"The Beatles<span>Band</span>"
Of course I would need to query freebase.com from that PHP. I mean:
+---------------+ +-----------+ +------------+
| | | | | |
| TextboxList +-------->| PHP +------->| Freebase |
| | | | | |
+---------------+ +-----------+ +------+-----+
|
JSON JSON |
TextboxList <--------+ freebase <----------+
Is this possible? Thanks!
Try this:
$response = array();
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
$myJSON = file_get_contents('http://www.freebase.com/private/suggest?prefix=' . urlencode($search));
$musicObj = json_decode($myJSON); // Need to get $myJSON from somewhere like file_get_contents()
foreach ($musicObj->result as $item)
{
$response[] = array($item->guid, $item->name, null, $item->name . '<span>'.$item->{'n:type'}->name.'</span>');
}
header('Content-type: application/json');
echo json_encode($response);
The first JSON-escaped result then gives:
["#9202a8c04000641f800000000003ac10","The Beatles",null,"The Beatles<span>Band<\/span>"]
But despite all this, you really don't need to use PHP at all to do this. You can do this all from JavaScript and avoid an extra trip to your server. If you supply the callback argument to freebase, it can create JSONP (which is JSON wrapped in a call to a function, using a function name of your choice) which you can obtain in jQuery and then manipulate further in JavaScript to your liking. But the above is per your original approach in using PHP.

Categories