Easiest Way to read a xls File with PHP - php

I got a xls file on a hosted Webserver and now I am trying to read it with PHP. It is not important to read the whole file. I just need a few cell information to work with them. So what is the best way to do that?

//Try PHP-ExcelReader
<?php
include 'excel_reader.php'; // include the class
$excel = new PhpExcelReader; // creates object instance of the class
$excel->read('excel_file.xls'); // reads and stores the excel file data
// Test to see the excel data stored in $sheets property
echo '<pre>';
var_export($excel->sheets);
echo '</pre>';
or
echo '<pre>';
print_r($excel->sheets);
echo '</pre>';

Related

php output directory was not found

I'm trying to save a file inside php: // output to send it as an answer (it's an excel).
The problem is that php does not find the directory, according to the documentation should be able to access it.
i add this validation to my code:
$folderName = 'php://output';
if(!is_dir($folderName)){
throw new FileNotFoundException($folderName . " directory not found.");
}
$objWriter->save($filePath);
and the exception has been throwed and return me:
"php://output directory not found.",
php://output is not a directory; it's an output stream. You use php://output to write stuff to the output buffer the same way echo or print does. For example, if you wanted to force the browser to display a PDF or an image straight away without saving it first, you would use php://output.
If you wanted to physically save the file in your filesystem then a proper path must be used.

echo or include multiple xml files in php page

I wish to create a list of XML files in a php file.
I need all my xml files to be included in my php file. I have this working see below.
<?php
header('Content-type: application/xml');
echo file_get_contents("exam1.xml");
when I try this it works well, now I try more than one.
<?php
header('Content-type: application/xml');
echo file_get_contents("exam1.xml");
echo file_get_contents("exam2.xml");
it dose not read any of the files.
I would try passing these files back in a JSON object.
Create an array of files and then json_encode() that array.
<?php
$f1 = file_get_contents("exam1.xml");
$f2 = file_get_contents("exam2.xml");
$response = array('files' => array($f1, $f2));
echo json_encode($response);
?>
Now you will have a simple json object that you can process in the javascript and place 1 or many xml file(s) whereever you want to on the page using straight forward javascript

cakephp upload file option does not get properties of filename

I m trying to upload xlsx file in cakePHP
View code
echo $this->Form->create('Program', array('type' => 'file'));
echo $this->Form->file('Program.avatar');
echo $this->Form->submit();
Controller code
$inputFileName = $this->request->data['Program']['avatar'];
var_dump($inputFileName);
Issue is output of var_dump does not give properties of file which i would like to use it for PHPExcel plugin. Instead $inputFileName outputs "string 'import.xlsx' (length=11)", due to which i m unable to use it for IOFactory
Could anyone please let me know where I m going wrong on this.
Thank you.
If you use var_dump it will put extra information into the output (as it is dumping the variables).
If you simply use
echo $inputFileName;
or
return $inputFileName;
These will return only the filename, you can also handle this directly through the $_FILES array or to stick with the CakePHP way you can simply get the information of the file from $this->request->data as explained here: http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#validating-uploads

provide latest xml file php

maybe someone can help me, i provide xml files witch are generated from a PHP DB query and each xml file has a unique name. Now i want to prepare a function like "get the latest xml file" but I don't know whats the best way!
$xml = simplexml_load_file('test.xml');
I found this function but there i have to know the exact name!
or ist something like this possible:
$xml = simplexml_load_file('test.php');
and in the test.php i have a function to get the last name, but how to i provide the xml data?
Some keywords how i can find a solution in google would be very helpful!
The first parameter to that function is a string of the filename. The file should be the XML file to load, so you cant use another php file.
http://php.net/manual/en/function.simplexml-load-file.php
So you need to get the filename as a string first by using a variable. You should be able to copy the code in your test.php file, then save the filename instead of echoing it out. Then you use that variable when loading the xml file.
e.g.
function get_latest_filename()
{
//contents of your test.php file should set this variable
$latest_filename = 'the_latest_file.xml';
return $latest_filename;
}
$latest = get_latest_filename();
$xml = simplexml_load_file($latest);
here the finish solution that worked for me
i protected the directory with .htaccess and inside i store all my generated xml files and also the getLastXml.php file!
the getLastXml.php
function get_last_file() {
$lastFileTime = 0;
foreach (glob("*.xml") as $filename) {
if ($lastFileTime<filemtime($filename))
{
$lastFileTime = filemtime($filename);
$lastFileName = $filename;
}
}
return $lastFileName;
}
$lastXmlFile = get_last_file();
header ("Content-Type:text/xml");
echo file_get_contents($lastXmlFile);
the functions get_last_file() returns the name of the latest created xml file and
header ("Content-Type:text/xml");
displays xml in the php file
echo file_get_contents($lastXmlFile);
loads the content of the xml file and display it
simplexml_load_file("http://username:passwort#urlToTheDirectory/getLastXml.php");
loads the xml data with

PHP: Is there a correct method for saving configuration data?

I have a config.inc file in a web application that I am building. It contains an array with configuration values for things like the MySQL database, etc. I would like these to be entered by using a simple form, that asks for the server, login/password for the database, etc, then these get written to the configuration file.
Is there a preferred method of doing this? I am not sure how to write to a file, and update an array.
You just want writing, correct? Is it a serialized array or is it parsed?
One way to read a config file is parse_ini_file(). I wouldn't necessarily call it preferred, but it's a method. You'd still need to write the file.
Another way would to write a "config.inc.php" and just include it in, to write it you'd just output actual PHP code (e.g. $var = "myval";).
This is a way you could write a simple "output" function that took an array of configuration values and output them as name=value, assuming $config was an associative array.
foreach ($config as $name => $value) {
$output .= $name . '=' . $value . "\n";
}
if (!file_put_contents($filename, $output)) {
die("Error writing config file.");
}
There's a lot of decent ways to do it. It's really based on your requirements. Does it need to be in a specific format or do you have leeway?
It is not recommended to modify PHP configuration files via your application, you should use CSV files or a database table.
In case you want to save it in a CSV file then I suggest you keep a CSV file for each configuration type (e.g CSV file for database configurations) and always overwrite the previous one using file_put_contents
Save data example:
$csvStructure = array("dbUser","dbPassword","dbHostname","dbPort"); // array used for both loading data and saving it
$csvData = array();
foreach ($csvStructure as $field) {
$csvData[] = $_POST[$field]; // so it'd get $_POST["dbUser"],$_POST["dbPasword"], etc..
}
file_put_contents("filename",implode("\t",$csvData));
Load data example:
$csvStructure = array("dbUser","dbPassword","dbHostname","dbPort"); // array used for both loading data and saving it
$dbConfig = array();
$csvData = explode("\t",file_get_contents("filename"));
foreach ($csvStructure as $key => $field) { // $key would have the location of the requested field in our CSV data (0,1,2, etc..).
$dbConfig[$field] = $csvData[$key]; // populate $dbConfig["dbUser"],$dbConfig["dbPasword"], etc..
}
I believe using an ini file is a wise option, because user, password, schema, paths, etc. are things that usually will be modified by hand, so using var_export isn't because modifying it by hand it's not so clean and may crash your application if you make a mistake in the PHP syntax.
But parsing big ini files can be expensive, so it would be OK to cache the ini with var_export() or serlialize(). It's a better choice, I think, and read the ini only when the cache file doesn't exists.
PHP has a dedicated function for this, its called var_export();
Just do:
file_put_contents("config.php",var_export($config,true));
Well, to write a file, fwrite() php function does exactly what you want. From its PHP.NET documentation page (see example below).
Now, on the question as to what to output to that file - I'm assuming that file will have to be included as a configuration .php file into the rest of the project. I'm imagining you'll do something like this - where you're creating strings with PHP code on the fly, based on the submitted form:
$strDatabaseConfig = "\$databaseConfig = array('" . $_POST['login'] . "," . $_POST['password'] . "');";
And here's the snippet for fwrite:
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// 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, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
Here's one way: wp-admin/setup-config.php from WordPress.
I prefer to have a file with a bunch of define statements.
These are constants globally available (and of course immutable) which is what you need for configuration settings.
Constants offer better memory management and efficiency in reading as they don't need the extra memory required by a variable so that it can be changed.
Let's say your config.inc file looks like this:
$config = array(
'blah' => 'mmm',
'blah2' => 'www',
//...
);
You want to update it, so you create a simple form, fill text fields with current values. PHP script that overwrites current configuration could looks like this:
$newConfig = ...; // data from form - of course validate it first
$config = ...; // data from config.inc
$config = array_merge($config, $newConfig);
file_put_contents('config.inc', '<?php $config = ' . var_export($config, true));
And you're done.

Categories