I want to download database table column fields as CSV in Zend Framework. Are there any ZF libraries for this?
There are other questions here on SO that addresses this specific subject, but none of them provide me enough detail. Could someone please describe in detail how to do it?
I'll assume you have a standard DbTable model for your table. Get the table information using the info() method
//the following is pseudocode and not meant to be copied directly, intended to guide
public function indexAction() {
$model = new Application_Model_DbTable_MyTable();
//This returns an array of table info
$info = $model->info();
//prepare the data so each line can be saved
$data = $info['name'] . ',' . $info['primary'];
//then write each line to the database, I usually use a function from
// a utility class or a protected function
//I would normally build an array of the data I want saved and then
//iterate over the array saving as I go.
$save = $this->_writeToFile($filename, $data);
}
//the following function is not pseudocode
protected function _writeToFile($filename, $content) {
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $content) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($content) to file ($filename) <br />";
//close file
fclose($handle);
} else {
echo "The file $filename is not writable";
}
}
Hope this points you in the right direction.
Related
1.8.0"
the goal of my web application is to have a button that the user clicks on.
The code behind will start to scan all the folders that are in the main rdv folder.
in the rdv folder it contains three folders named 1000, 1001, 1002 these contain .xlsx files.
retrieves the last file .xlsx saved in each of the folders
but after that it doesn't work.
Fatal error: Uncaught PHPExcel_Reader_Exception: Could not open 2.xlsx
for reading!
so how i can fix the fatal error and how is possible to read the file to continue the code, i want to get 3 values in the .xlsx file and insert into my database.
thank you for your time.
include 'database.php';
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
// receives the 'someAction' value from the index page button.
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
{
func();
}
function func()
{
//calcul the nomber of folder in folder rdv
$howManyFolder = count(glob('rdv/*', GLOB_ONLYDIR));
//retrieves the last file saved in each of the folders and insert into database
for ($i = 0; $i < $howManyFolder; $i++) {
$files = scandir("rdv/100$i", SCANDIR_SORT_DESCENDING);
echo "Recover all files in the folder 100" . $i . "<br>";
print_r($files ); echo "<br>";
echo "get the last file inserted in the folder at index 0 <br>";
$newest_file = $files[0]; print_r($newest_file); echo "<br>";
//load the file .xlsx (but the code bug here -_-)
$objExcel=PHPExcel_IOFactory::load($newest_file);
//get all value insinde the .xlsx file
$dossier = $objExcel->getActiveSheet()->getCell('A3')->getValue();
$facture = $objExcel->getActiveSheet()->getCell('B21')->getValue();
$date = $objExcel->getActiveSheet()->getCell('Q1')->getValue();
//call function to insert these values inside dataBase.
insertInto($dossier, $facture, $date );
}
}
XML Parser:
https://www.php.net/manual/en/book.xml.php
Parsing an XML document: https://www.php.net/manual/en/function.xml-parse.php
<?PHP
$stream = fopen('large.xml', 'r');
$parser = xml_parser_create();
// set up the handlers here
while (($data = fread($stream, 16384))) {
xml_parse($parser, $data); // parse the current chunk
}
xml_parse($parser, '', true); // finalize parsing
xml_parser_free($parser);
fclose($stream);
I have a WordPress issue and want to simply write log messages to a text file. I am aware that error_log exists, but want to have a more segregated log file for different messages.
I am using wp_filesystem->put_contents, and it DOES write to the file and succeeds, but it ONLY outputs the last call's data.
I have the following method:
public static function log_message($msg) {
error_log($msg);
require_once(ABSPATH . 'wp-admin/includes/file.php');
global $wp_filesystem;
if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
$creds = request_filesystem_credentials( site_url() );
wp_filesystem($creds);
}
$bt = debug_backtrace();
$caller = array_shift($bt);
$logStr = date("Y-m-d hh:ii A",time())." - ".$caller['file'].":".$caller['line']." - ".$msg;
$filePathStr = SRC_DIR.DIRECTORY_SEPARATOR.$logFileName;
$success = $wp_filesystem->put_contents(
$filePathStr,
$logStr,
FS_CHMOD_FILE // predefined mode settings for WP files
);
if(!$success) {
error_log("Writing to file \"".$filePathStr."\" failed.");
} else {
error_log("Writing to file \"".$filePathStr."\" succeeded.");
}
}
I call it using:
log_message("\nTest 1");
log_message("\nTest 2");
log_message("\nTest 3");
The output is ALWAYS ONLY Test 3 with the other invocations being ignored yet, their output appears in the debug.log as well as all the success messages.
Why would this be?
Looking at the WPCodex for the source code of this, it uses fwrite behind the scenes. The file is closed in this code, and I cannot use any "flush" technique.
Is there a way to figure this out?
I found that the source of WP_Filesystem uses file_put_contents (as the name does suggest), and I assumed this is for APPENDING to the file's data.
This is incorrect.
This function is to take data, and then WRITE it to the file, erasing prior data.
Mainly useful for creating resources, downloading a file, etc.
If I want to APPEND to a file, I need to use 'fwrite'.
This post describes that.
This is the example to APPEND to a file:
$filepath = '\path\to\file\';
$filename = 'out.log';
$fullpath = $filepath.$filename;
if(file_exists($fullpath)) {
$file = fopen($filepath.$filename, "a");//a for append -- could use a+ to create the file if it doesn't exist
$data = "test message";
fwrite($file, "\n". $data);
fclose($file);
} else {
error_log("The file \'".$fullpath."\' does not exist.");
}
The fopen docs describe this method and it's modes.
I have a Microsoft Word file that I am using as a template. (testingsample.docx) The plan is to use form input values to create a lease agreement. The code I found below works very well for opening up the .docx file and finding and replacing the required strings. The problem is it only works once. The first time it is ran, it overwrites my template. I am trying to find a way to open testingsample.docx, make the required string changes, and save the archive as testingsamplecopy.docx without altering testingsample.docx.
Thanks in advance for any help!
// Create the Object.
$zip = new ZipArchive();
$inputFilename = 'testingsample.docx';
// Open the Microsoft Word .docx file as if it were a zip file... because it is.
if ($zip->open($inputFilename, ZipArchive::CREATE)!==TRUE) {
echo "Cannot open $inputFilename :( "; die;
}
// Fetch the document.xml file from the word subdirectory in the archive.
$xml = $zip->getFromName('word/document.xml');
// Replace the strings
$xml = str_replace("1111","Tenant Name Here",$xml);
$xml = str_replace("2222","Address Here",$xml);
// Write back to the document and close the object
if ($zip->addFromString('word/document.xml', $xml)) { echo 'File written!'; }
else { echo 'File not written. Go back and add write permissions to this folder!l'; }
$zip->close();
header("Location: testingsample.docx");
?>
Just copy from the template file to the target file, then open the target file and not the template.
Also, I changed the code at the header line to use the variable of the name of the file and not a static one.
<?php
// Create the Object.
$zip = new ZipArchive();
$templateFilename = 'testingsample.docx';
$inputFilename = 'testingsamplecopy.docx';
if(!copy($templateFilename, $inputFilename)) {
die("Could not copy '$templateFilename' to '$inputFilename');
}
// Open the Microsoft Word .docx file as if it were a zip file... because it is.
if ($zip->open($inputFilename, ZipArchive::CREATE)!==TRUE) {
echo "Cannot open $inputFilename :( "; die;
}
// Fetch the document.xml file from the word subdirectory in the archive.
$xml = $zip->getFromName('word/document.xml');
// Replace the strings
$xml = str_replace("1111","Tenant Name Here",$xml);
$xml = str_replace("2222","Address Here",$xml);
// Write back to the document and close the object
if ($zip->addFromString('word/document.xml', $xml)) { echo 'File written!'; }
else { echo 'File not written. Go back and add write permissions to this folder!l'; }
$zip->close();
// I also chaned this to use your variable instead of a static value.
header("Location: $inputFilename");
?>
I have a script with a mysql query which saves a file called invoice.xml every day automatically by running a cron job. In case no data is found a no_orders.txt is saved.
I would like this file not be saved to the same folder as the script.php file is in but to a subfolder called invoices.
The renaming of the old invoice.xml is done with the following code
// rename old file
$nowshort = date("Y-m-d");
if(file_exists('invoice.xml')) {
rename('invoice.xml','invoice_'.$nowshort.'.xml');
}
The saving is done with the following code:
if($xml1 !='') {
$File = "invoice.xml";
$Handle = fopen($File, 'w');
fwrite($Handle, $xml1);
print "Data Written - ".$nowMysql;
fclose($Handle);
#print $xml;
die();
} else {
print "No new orders - ".$nowMysql;
$File = "no_orders_".$nowshort.".txt";
$Handle = fopen($File, 'w');
fclose($Handle);
die();
}
Could I please get assistance how to save this file to a subfolder. Also the renaming of the existing file would need to be within the subfolder then. I have already tried with possibilities like ../invoice/invoice.xml but unfortunately without any success.
Thank you
Just give the path of file 'invoice.xml' to $File.
Otherwise create some $Dir object which will point to Folder named 'invoice', then use accordingly
Use __DIR__ magic constant to retrieve your script.php directory, then you can append /invoice/invoice.xml .
Example if path to your script php something like this:
/var/www/path/to/script.php
$currentDir = __DIR__; //this wil return /var/www/path/to
$invoicePath = $currentDir.'/invoice/invoice.xml';
I have a piece of code written in codeigniter that reads a csv file and is supposed to write to a JSON file which i can read from later. The problem is that if I set a path for the file, the code fails but it works if i don't save a filepath.
Here is my code
$csvfile = array('csvfile' => $this->upload->data($upload_field_name));
$csvdata = $this->csvreader->parse_file($csvfile['csvfile']['full_path']);
$data['jsondata'] = json_encode($csvdata);
$path = '../uploads/'.$current_user_name.'.json';
if ( ! write_file( $path, $data['jsondata'],'w+' ) )
{
echo "File writing failed";
echo $path;
}
else
{
$this->load->view('dashboard');
}
I have looked for possible solutions but couldn't find any.