I am trying to add data into excel file which is extracted from wordpress database, Actually I am trying to export data (tags) from database into excel file. And I write down a code, but when I click on generate button. This generates empty file.
Please guys check what I am doing wrong.
Codes are below:
if (check_admin_referer('tag-export'))
{
$blogname = str_replace(" ", "", get_option('blogname'));
$date = date("m-d-Y");
$xls_file_name = $blogname."-exported-tags-".$date;
$tags = get_terms( 'post_tag' , 'hide_empty=0' );
$count = count($tags);
if ( $count > 0 )
{
echo 'name' . "\t" . 'slug' . "\n";
foreach ( $tags as $tag )
{
echo $tag->name . "\t" . $tag->slug . "\n";
}
}
ob_clean();
echo $xls_file;
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=$xls_file_name.xls" );
exit();
}
The above codes are not writing data into excel file. please check and let me know.
Just based on your existing code:
if (check_admin_referer('tag-export'))
{
$blogname = str_replace(" ", "", get_option('blogname'));
$date = date("m-d-Y");
$xls_file_name = $blogname."-exported-tags-".$date;
$tags = get_terms( 'post_tag' , 'hide_empty=0' );
$count = count($tags);
$xls_file = '';
if ( $count > 0 )
{
$xls_file .= 'name' . "\t" . 'slug' . "\n";
foreach ( $tags as $tag )
{
$xls_file .= $tag->name . "\t" . $tag->slug . "\n";
}
}
ob_clean();
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=$xls_file_name.xls" );
echo $xls_file;
exit();
}
A more general suggestion, not a solution for your coding problem: create an HTML table file from the code and then open it in Excel for conversion. Doing it so you'll have a better understand on what's going on with your code: you can add var_dumps or simply debug it like a normal web page.
Having an html table is also useful because excel works quite well in converting it to XLS files.
After your HTML file works well, then you can apply necessary formatting/header to the code in order to create the xls file from scratch.
Related
First, I have a few knowledge in PHP, and that is all I could do with my excel export (see attached code below)
It works, but I want to export that excel file with 2 more sheets, I've googled a lot but could not customize the code to insert in it, please, help me if you can
Thank you
<?php
$filename = time().".csv";
header ( 'HTTP/1.1 200 OK' );
header ( 'Date: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Last-Modified: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Content-Type: application/vnd.ms-excel') ;
header ( 'Content-Disposition: attachment;filename='.$filename);
ExportFile1($main_exce);
function ExportFile1($records) {
$do = false;
if(!empty($records)){
foreach($records as $down){
$heading = true;
foreach($down as $row) {
if($heading) {
// display field/column names as a first row
$heading = false;
if(!$do){
$d = implode("\t", array_values($row)) . "\n";
print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
$do = true;
}
}else{
$d = implode("\t", array_values($row)) . "\n";
print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
}
}
// $d = "\t\n\t\n\t\n";
// print chr(255) . chr(254) . mb_convert_encoding($d, 'UTF-16LE', 'UTF-8');
}
}
}
exit;
?>
The reason you can't make this work is that you are not creating an Excel export here.
You're creating a plain-text, tab-delimited file. Excel can import files in that format, but it's not a true Excel file. It's a simple flat file, and as such, it doesn't support multiple worksheets, unlike a real Excel file.
If you want to solve this, you need to rewrite this code so that it outputs a file which is in the real Excel file format - it's considerably more complex than a tab-delimited text format. There are various libraries available for PHP which can help you easily create real Excel files in xlsx format. Recommendations are off-topic here but they are not hard to find using a search engine.
how can I restrict users to upload files that are Pure HTML Only.
I'm currently creating an online editor in PHP that would produce a web page which can be printed to PDF. As such, I have some HTML files that need to be dynamically included in the web page. This is because manually adding them through the online editor would take a long time as they include a lot of content, plus they contain static data which need not be changed. Think of them as presets.
Now the problem occurs when I let the users upload their own presets. As far as I know, any file with the .html extension can hold PHP code. How can I make sure that no PHP code lies within the uploaded file? Is it even possible to escape PHP tags using PHP?
Code example:
//User fills the PDF editor form and submits it.
is_logged(); // Login check and setting user info variables, redirects if not logged in.
if ( !isset( $_POST['gen-page'] ) {
custom_redirect( MAIN_PATH );
}
$content .= "<html>";
$content .= "<head>";
$content .= "<meta charset='utf-8'>";
$content .= "<meta name=viewport' content='width=device-width, initial-scale=1'>";
$content .= "<title>"$user_name"</title>";
$content .= file_get_contents( MAIN_PATH . '/uploads/' . $user_id . '/' . $user_style . '.html' ); // Contains style details.
$content .= "</head>";
$content .= "<body>";
for ($inputs as $input) { // Inputs is an array that was posted by the user.
$content .= "<p>" . $input . "</p>";
}
$content .= file_get_contents( MAIN_PATH . '/uploads/' . $user_id . '/' . $user_file . '.html' ); // The preset that the user has uploaded.
$content .= '</body>';
$filename = MAIN_PATH.'viewable/view-' . $user_id . '.html';
file_put_contents( $filename, $content );
custom_redirect( MAIN_PATH.'viewable/view-' . $user_id . '.html' );
I am currently developing an App for my school to record Class Cleanliness Results for each class, so I need to convert the results collated in MySQL table into Microsoft Excel using PHP, preferably also able to be opened by a Android OS Phone.
I used the following PHP code:
<?PHP
$mysqli_user = "(user)";
$mysqli_password = "(password)";
$mysqli_host = "(host)";
$mysqli_database = "(database)";
$filename = "grading_results_" . time() . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$link = mysqli_connect($mysqli_host,$mysqli_user,$mysqli_password,$mysqli_database);
$query = 'SELECT * FROM (table_name)';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)){
print implode("\t", $row) . "\n";
}
mysqli_close($link);
?>
This is how my table looks like in phpMyAdmin:
https://www.dropbox.com/s/7pr3gh06zta5d8u/Snip20150618_2.png?dl=0
This is how the Excel file looks like after I used this code to convert.
https://www.dropbox.com/s/571m9lfj64tklpc/Snip20150618_3.png?dl=0
Why is there no columns and rows? I need the Excel file to be exactly the same formatting and style as the table in phpMyAdmin. Can anyone help edit my code instead of providing me a brand new code?
Thanks in advance for your answers!
Manual
Run tour localhost and log in to phpMyAdmin
Click on your database then click on the table which you want to get
Excel.
then
then press GO button
With Code
define ("DB_HOST", "localhost");
define ("DB_USER", "root");
define ("DB_PASS","");
define ("DB_NAME","DATABASE_NAME");
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
then
$setCounter = 0;
$setExcelName = "download_excal_file";
$setSql = "YOUR SQL QUERY GOES HERE";
$setRec = mysql_query($setSql);
$setCounter = mysql_num_fields($setRec);
for ($i = 0; $i < $setCounter; $i++) {
$setMainHeader .= mysql_field_name($setRec, $i)."\t";
}
while($rec = mysql_fetch_row($setRec)) {
$rowLine = '';
foreach($rec as $value) {
if(!isset($value) || $value == "") {
$value = "\t";
} else {
//It escape all the special charactor, quotes from the data.
$value = strip_tags(str_replace('"', '""', $value));
$value = '"' . $value . '"' . "\t";
}
$rowLine .= $value;
}
$setData .= trim($rowLine)."\n";
}
$setData = str_replace("\r", "", $setData);
if ($setData == "") {
$setData = "no matching records found";
}
$setCounter = mysql_num_fields($setRec);
//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName."_Report.xls");
header("Pragma: no-cache");
header("Expires: 0");
//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";
More About Code
SELECT id, name, email INTO OUTFILE '/tmp/ram.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\’
LINES TERMINATED BY '\n'
FROM users WHERE id=1
Here /tmp/ is address where u want to store the csv
<?php
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
// print your data here. note the following:
// - cells/columns are separated by tabs ("\t")
// - rows are separated by newlines ("\n")
// for example:
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
?>
// You can fetch the data from the database and display in the table. Then put the table in echo to get Excel file.
How can I determine if a PDF file is corrupt (not openable) in PHP? I have downloaded thousands of PDFs via CURL and a small number are incomplete.
$part = 'pdffile.pdf';
$escPath = str_replace( " ", "\\ ", escapeshellcmd( $part ) );
$out = shell_exec( 'pdfinfo ' . $escPath . ' 2>&1' );
if( $out != null && !preg_match( '~Error~i', $out ) )
echo "GOOD: $part\n";
else
echo "CORRUPT: $part\n";
I can only find a way to do this via the command line. The second line is required to escape file paths.
I need to export all posts from certain category (that contains thousands posts) to a text document. And then someone will make corrections and changes in this document, and after this I have to enter all the updated posts to WP. So I decided that the best way is to make a XML document (by this way it could be easy to enter the posts back).
So my code is:
require_once(dirname(__FILE__) . '/wp-blog-header.php');
$counter = 0;
$recorded = array();
$double=0;
$handle = fopen("all_posts.xml", "w");
fwrite($handle, "<all_posts>" . "\r\n"); // the root XML tag
// get all the categories from the global category
$global_cat = get_categories(array("child_of"=>5, 'pad_counts'=>true, 'hierarchical' =>
false));
foreach($global_cat as $child_cat){
global $post;
$args = array('numberposts' => 50000,'cat' => $child_cat->cat_ID);
print_r($child_cat); echo "<br>" . $counter ."<br>";
$q_posts = get_posts($args);
foreach($q_posts as $post){
setup_postdata($post);
if( in_array($post->ID, $recorded ) ) {continue;}
$recorded[] = $post->ID;
$counter++;
$title = get_the_title();
$cur_categories = get_the_category();
$cur_tags = get_the_tags();
$d = get_the_date();
$cont = get_the_content();
fwrite($handle, "<post>" . "\r\n");
fwrite($handle, "<title>" . $title . "</title>" . "\r\n");
fwrite($handle, "<id>" . $post->ID . "</id>" . "\r\n");
fwrite($handle, "<cur_cat>" . $child_cat->name . "</cur_cat>" . "\r\n");
fwrite($handle, "<categories>\r\n");
foreach ($cur_categories as $cat) {
fwrite($handle, "<cat>" . $cat->cat_name . "</cat>");
}
fwrite($handle, "\r\n</categories>" . "\r\n");
fwrite($handle, "<tags>\r\n");
foreach ($cur_tags as $tag) {
fwrite($handle, "<tag>" . $tag->name . "</tag>");
}
fwrite($handle, "\r\n</tags>" . "\r\n");
fwrite($handle, "<date>" . $d . "</date>\r\n");
fwrite($handle, "<content>\r\n" . $cont . "</content>\r\n\r\n");
fwrite($handle, "</post>" . "\r\n");
}
}
fwrite($handle, "</all_posts>");
fclose($handle);
The problem is, that because there is something like 10,000, the server does not give responce [I think it because that the xml file become to big or because of the excessively long time of procceng php script]. Only when I try to export posts from category that has only something like 2000 posts it works well.
What is the way to fix it?
On the top of your code set the max_execution_time to unlimited (or for some minutes) ...
ini_set('max_execution_time', 0);
Try even to boost the memory limit used by PHP
ini_set('memory_limit', '100M');
You are probably hitting the time limit for scripts. This can sometimes be changed with set_time_limit.
Otherwise you can limit it to export a few hundred pages at a time. Just change the offset option for get_posts between runs.
Try this.
Where you have:
$args = array('numberposts' => 50000,'cat' => $child_cat->cat_ID);
put
$args = array('numberposts' => 50000,'cat' => $child_cat->cat_ID, 'post_status' => 'publish' );
This will make sure you only have the posts that are published. Is this what you want? or do you want all of them.
If you want all of them, try putting all of the code in a while loop based on the categories and insert the category name into the name of the file therefore having multiple files but then you can still call all of them individually. This is probably your best bet since the file would be too large.
Ethan Brouwer