I've asked a similar question previously but Ive been told my question is just me being lazy so let me rephrase.
Ive been using a PHP class script to enable me to export my SQL data to a .xls file but the resultant excel file doesnt display any values and no error is being displayed on the webpage itself.
The class file Im using is documented in the link below:
http://web.burza.hr/blog/php-class-for-exporting-data-in-multiple-worksheets-excel-xml/
And Ive incorporated it in my site as follows
$dbase->loadextraClass('excel.xml');
$excel = new excel_xml();
$header_style = array(
'bold' => 1,
'size' => '14',
'color' => '#000000',
'bgcolor' => '#ffffff'
);
$excel->add_style('header',$header_style);
if(isset($_POST['fec_save']))
{
if($_POST['reporttype']=='films')
{
$films = $dbase->runquery("SELECT datetime,title,country_of_origin,language,runningtime,(SELECT name FROM fec_client WHERE filmid = fec_film.filmid) AS client, (SELECT rating_decision FROM fec_rating_report WHERE filmid = fec_film.filmid) AS rating FROM fec_film WHERE datetime >= '".strtotime($_POST['fromdate'])."' AND datetime <= '".strtotime($_POST['todate'])."'",'multiple');
$filmcount = $dbase->getcount($films);
//continue with excel buildup
$columns = array('Date','Title','Origin','Language','Minutes','Client','Rating');
$excel->add_row($columns,'header');
for($i=1; $i<=$filmcount; $i++)
{
$film = $dbase->fetcharray($films);
$excel->add_row($film['datetime'],$film['title'],$film['country_of_origin'],$film['language'],$film['runningtime'],$film['client'],$film['rating']);
}
$excel->create_worksheet('From_'.str_replace(' ','',$_POST['fromdate']).'_to'.str_replace(' ','',$_POST['todate']));
$xml = $excel->generate();
$excel->download('FilmsClassified_from_'.str_replace(' ','',$_POST['fromdate']).'_to'.str_replace(' ','',$_POST['todate']));
}
}
I would like some assistance as to what I maybe doing wrong.
Thanks
Too long to post as a comment:
$xml = $excel->generate();
creates all the xml file content as a string and stores it in $xml
while
$excel->create_worksheet('From_'.str_replace(' ','',$_POST['fromdate']).'_to'.str_replace(' ','',$_POST['todate']));
creates the xml and directs it to output, with appropriate headers for downloading.
So you're not using the class correctly, as that's unnecessary duplication of work.
Related
Using PhpWord library, please tell me if it is possible to insert an image in front of text and on every page, in the same position, when creating a new docx file.
You could use a development version which implements this:
Have a look at this issue: https://github.com/PHPOffice/PHPWord/issues/939
This pull request implements this: https://github.com/PHPOffice/PHPWord/pull/1084
here is a simple example to illustrate what I meant with using global header to place an image in the top of every page (with single section containing a long table):
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$header = $section->addHeader();
$header->addImage('resources/PhpWord.png', array('width' => 80, 'height' => 80, 'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::START));
// generate long table just for demo that spans over multiple pages
$table = $section->addTable();
for ($i = 0; $i < 200; $i++) {
$table->addRow();
$table->addCell(4500)->addText('dummy');
$table->addCell(4500)->addText("contents $i");
}
I have a database field in SQL Server 2012 database. They can contain PDF, WORD, Excel or image files. My Blob field type is varbinary(max). My code works fine using ColdFusion, however I have tried to convert it to PHP and it doesn't seem to be working. Below is the code I am using. Can someone tell me what I am doing wrong?
The example below is just for a word document and when the Word application is launched, I get a "File Conversion" dialog box asking me to select the encoding that makes the document readable none of which makes any difference. The preview window shows a bunch of garbage.
<?PHP
$aserverName = "SQ-ENT12-D01\Dev";
$aconnectionInfo = array( "Database"=>"Event_Registration", "UID"=>$uid, "PWD"=>$pwd, "CharacterSet"=>"UTF-8");
$aconn = sqlsrv_connect( $aserverName, $aconnectionInfo);
// Get the record where the binary data is
$GetBlobSQL = "select * from Congress where Congress_ID = 102";
$GetBlob = sqlsrv_query($aconn, $GetBlobSQL, array(), array('Scrollable' => 'buffered'));
$GetBlobRecordCount = sqlsrv_num_rows($GetBlob);
$brec = sqlsrv_fetch_array( $GetBlob, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, 0);
$WhatFile = ($brec['Document_Agenda']);
$WhatBlob = ($brec['AD_Agenda']);
$MyExt = substr($WhatFile, -4);
$WhatExt = strtolower($MyExt);
header('Content-type: application/ms-word');
header('Content-Disposition: attachment; filename="'.$WhatFile.'"');
echo $WhatBlob;
?>
I know the file or data in the database is not corrupted because my original ColdFusion code works fine to retrieve and display the data.
Try removing "CharacterSet"=>"UTF-8" from the $aconnectionInfo. You may be confusing the database and causing conversions to take place that are not needed or desired.
I want to convert the array data into HTML format and want to save the file as a .html file. How can I do this?
Suppose the array is:
Array
(
[0-50] => 880
[50-100] => 5
[100-150] => 1
[550-600] => 1
)
And I am writting a file like this:
<?php
$file = fopen("abc.html","w");
?>
I can write this file as a CSV format easily but how can I do this to store a html file from data?
my expected result is -
Distance trips
0-50 880
50-100 5
100-150 1
550-600 1
distance and trips here are the table header and in distance field all are the keys of the array and in trips all are the values of the array.
Suppose i have written the data into this file ->
$html['head'] = '<html><head></head><body>';
$html['content'] = "<table><tr style='background-color:cyan'><td>Distance</td><td>total Trips</td></tr>";
foreach($de as $key=>$value)
{
$html['content'] .="<tr style='background-color:yellow'><td>$key</td><td>$value</td></tr>";
}
$html['foot'] = '</table></body>';
file_put_contents("abc.html", $html);
Now i wanted to append this file with this data ->
$html['head'] = '<html><head></head><body>';
$html['content'] = "<h2>Data Regarding 0 - 50 km distance</h2>
<table width=900 border=5>
<tr style='background-color:cyan font-size:24px'>
<td>S.No</td>
<td>Customer Id</td>
<td>Total Distance</td>
<td>Total Trips</td>
<td>Average Speed</td>
";
foreach($dec as $result=>$value) {
$html['content'] .= "<tr style='background-color:lightgreen'><td>$value[cid]</td><td>$value[totalDistance]</td><td>$value[totalTrips]</td><td>$value[avgSpeed]</td></tr>";
}
$html['foot'] = '</table></body></html>';
Since you place dynamic information in static HTML document, you need to rewrite this information on each edit.
Use some PHP library to read HTML file (like HTML DOM Parser)
Gather all table information from HTML file.
Append new information (or insert where needed).
Write new content to HTML file.
I suggest to save this information to some structured format (like json file or database) and when showing information, just read this data. It would be much easier to implement.
E.g. rewriting data in json file:
$json = json_decode(file_get_contents('data.json'), true);
$json = array_merge($json, $newData);
file_put_contents(json_encode($json));
For the first table you want to put in a html file, this will do the work using your methodology :
<?php
//Creating the array
$de = Array("0-50" => 880,
"50-100" => 5,
"100-150" => 1,
"550-600" => 1
);
//creating the array corresponding to html code
$html = array();
//Creating the header
$html['head'] = '<html><head></head><body>';
//creating content - table header
$html['content'] = "<table><tr style='background-color:cyan'><td>Distance</td><td>total Trips</td></tr>";
foreach($de as $key=>$value)
{
$html['content'] .="<tr style='background-color:yellow'><td>$key</td><td>$value</td></tr>";
}
//footer
$html['foot'] = '</table></body>';
//no need to use fopen because file_put_contents manages that.
file_put_contents("abc.html", $html);
?>
But for the second part of your question, the same logic will work, just be careful how you use array, specially here :
foreach($dec as $result=>$value)
{
$html['content'] .= "<tr style='background-color:lightgreen'><td>$value[cid]</td><td>$value[totalDistance]</td><td>$value[totalTrips]</td><td>$value[avgSpeed]</td></tr>";
}
You should write it this way :
foreach($dec as $result=>$value)
{
$html['content'] .= "<tr style='background-color:lightgreen'><td>".$value['cid']."</td><td>".$value['totalDistance']."</td><td>".$value['totalTrips']."</td><td>".$value['avgSpeed']."</td></tr>";
}
Hi hope it helped.
What you are looking for is the Append Mode.
a => Open for writing only;
Or
a+ => Open for reading and writing;
What this mode does is "place the file pointer at the end of the file. If the file does not exist, attempt to create it."
So your fopen line becomes ...
$file = fopen("abc.html","a");
This ways you can always append whatever you want.
I'm trying to write PHP to insert lots of content into my website's drupal 6 database.
The content type has got 3 custom fields:
field_theme_preview_demo_link - text field
field_theme_preview_content_styl - text selector
field_theme_preview_thumb - image field with an 'alt'
I just copied the images over to the correct directory manually.
I created the content type (and manually inserted some content to confirm it was all ok).
I then found some code sample for programatically inserting content...
Creating Drupal CCK content programatically/ via API
and
http://drupal.org/node/458778#comment-1653696
(for this one I couldnt understand the mod that is suggested for D6).
I tried to modify it but couldnt get it to work - it does create the new content but the image field is blank. (To run this code I just paste into the 'Execute PHP Code' block.)
global $user;
$newnode = new stdClass();
$newnode->title = 'New node title';
$newnode->body = "the body";
$newnode->uid = $user->uid;
$newnode->type = 'theme_preview';
$newnode->status = 1;
$newnode->promote = 0;
$newnode->active = 1;
$newnode->field_theme_preview_demo_link[0]['value'] = 'the link';
$newnode->field_theme_preview_content_styl[0]['value'] = 'Books';
$newnode->field_theme_preview_thumb = array(
array(
'fid' => 'upload',
'alt' => 'the alt',
'filename' => 'sites/default/files/theme_preview_thumbs/41531.jpg',
'filepath' => 'sites/default/files/theme_preview_thumbs',
'filesize' => filesize('sites/default/files/theme_preview_thumbs/41531.jpg'),
),
);
node_save($newnode);
Setting the fid field to 'upload' is something that is done by a node's form when there actually is a file being uploaded. If you are programatically generating content, you will need to fetch the fid from somewhere else.
You will probably need to manually use the file api to enter a file from somewhere on the filesystem into the file database, and then draw your fid from the resulting object.
Use http://drupal.org/project/node_export this module to import or export content to particular content type, it really works for me and also image will be uploaded automatically.
One thing you have to consider for using this module, after importing nodes, make sure that images are matched with its content.
Using this module i have uploaded 100s of news article to my website from my local server site.
#Seth Battin, # Ayesh K, thanks for the tips,
working code...
global $user;
$newnode = new stdClass();
$newnode->title = 'New node title';
$newnode->body = "this is a new node, created by import function";
$newnode->uid = $user->uid;
$newnode->type = 'theme_preview';
$newnode->status = 1;
$newnode->promote = 0;
$newnode->active = 1;
$newnode->field_theme_preview_demo_link[0]['value'] = 'test 1';
$newnode->field_theme_preview_content_styl[0]['value'] = 'Books';
$field = field_file_save_file(
'sites/default/files/srcImage1.jpg',
array(),
'sites/default/files/theme_preview_thumbs');
if( !isset($field['data']) ) $field['data'] = array();
$field['data']['title'] = "the image title";
$field['data']['alt'] = "the image alt";
$newnode->field_theme_preview_thumb = array(0 => $field);
$newnode = node_submit($newnode);
node_save($newnode);
I have a file in .shp format and I need it to convert it to an Excel spreadsheet programmatically. I want to do this using PHP or JavaScript.
Once I've used small PHP lib ShapeFile, you can get it in phpclasses.org. Although it is a bit of not so good design, it works.
Here is a little example from my own code:
require_once 'lib/ShapeFile.inc.php';
$shp = new ShapeFile($filename, array('noparts' => false));
if ($shp->getError() !== '')
print_r($shp->getError());
else
{
$records = array();
while ($record = $shp->getNext())
{
$dbf_data = $record->getDbfData();
$shp_data = $record->getShpData();
//Dump the information
$obj = array(
'type' => $shp->getShpTypeName($record->getShpType())
);
$obj['shape'] = $shp_data;
$obj['meta'] = $dbf_data;
$records[] = $obj;
}
}
print_r($records);
So, after that $records contain all the data from shapefile. Of course, you will need some time to figure out what shapefile is and what data it can hold (assuming you are not familiar with it). Start from wikipedia. Actually there are bunch of arrays with some labels.
Then use some php excel lib (just seek in so) and you're done :)