I have a PHP generated page containing the results of a submitted form, what I would like to do is save this as a .doc file on the server.
After some googling I came across this code which I adapted:-
$myFile = "./dump/".$companyName."/testFile.doc";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
But the problem with this is that I would have to recreate the results in order to manually write them to the file and it doesn't seem very efficient.
So I continued to google and found the PHP manual which left me scratching my head frankly, however I eventually found this:-
ob_start();
// code to generate page.
$out = ob_get_contents();
ob_end_clean();
// or write it to a file.
file_put_contents("./dump/".$companyName."/testFile.doc",$out);
Which will create the file, but doesn't write anything to it. However this seems to be the way to do what (Based on the PHP manual) I want even if I can't get it to work!
Any advice? I don't mind googling if I can figure out a decent search term :)
This sould do it for you:
$cache = 'path/to/your/file';
ob_start();
// your content goes here...
echo "hello !"; // would put hello into your file
$page = ob_get_contents();
ob_end_clean();
$fd = fopen("$cache", "w");
if ($fd) {
fwrite($fd,$page);
fclose($fd);
}
It's also a great way to cache dynamic pages. Hope it helps.
Related
I have bunch of images file (.jpg) in a folder, then I want to list them to a single file text, I using php (xampp in windows).
This for list images name in my browser (it's working):
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
foreach (glob($file."\*.jpg") as $filenames) {
echo $filenames."<br />";
}
?>
This for create text file called 'images_list.txt' (not working):
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
foreach (glob($file."\*.jpg") as $filenames) {
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$data = echo $filenames."<br />";
fwrite($handle, $data);
}
?>
When I execute that script, appear warning message
"
Parse error: syntax error, unexpected 'echo' (T_ECHO) in D:\xampp\htdocs\rename_file_php\try_list_img.php on line 7"
If line 7, I change
$data = $filenames;
The file 'images_list.txt' will created, but only fill one image name listing in the file. Can anyone help me?
Sorry for my bad english.
Open file once and try to write data once:-
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
$data = '';
foreach (glob($file."\*.jpg") as $filenames) {
$data .= $filenames."\n";
}
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $data);
fclose($handle);
?>
You want to fopen() the file only once, so outside the loop. Otherwise you overwrite the content again and again. Take a look at this modified version:
<?php
$folder = 'F://images/upload/google/ready_45';
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die("Cannot open file: ". $my_file);
foreach (glob($folder . "/*.jpg") as $filename) {
$data = $filename . PHP_EOL;
fwrite($handle, $data);
}
fclose($handle);
One certainly could simplify that. For example by simply imploding the list of matched file names with a linebreak and then writing the result in one go:
<?php
$folder = 'F://images/upload/google/ready_45';
$data = implode(PHP_EOL, glob($folder . "/*.jpg"));
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die("Cannot open file: ". $my_file);
fwrite($handle, $data);
fclose($handle);
However the first (loop based) approach allows more flexibility, for example filtering or escaping.
Side notes:
using a normal slash as folder delimiter (/) instead of the insane backslash (\\) natively used in MS-Windows will save you a lot of hassle. PHP can work with both on a MS-Windows platform.
using a line break instead of the html linewrap makes more sense when writing into a file in most cases. Using PHP_EOL instead of a hard coded line break (\r\n) will make your code portable for systems using different types of line breaks (only MS-Windows uses \r\n for that).
I took the liberty to also fix some indentation and code styling issues. It definitely makes sense if programmers loosely agree on some standard to enhance readability of code.
This is all you need:
// Creates a newline separated list from the array returned by glob()
$files = glob ($folder.'/*.jpg');
$files = implode (PHP_EOL, $files);
∕∕ This is all that is needed to write something to a file.
file_put_contents ($my_file, $files);
The fopen() and all that is old, old code, which should be avoided whenever possible. Not only is this method simpler and easier to read, but it's also generally faster.
Note that you might want to wrap an IF statement around the last line, in order to handle any errors with writing that might crop up.
Following code is working fine, I have a images folder which is having some image files, please change the folder path and try the below code
<?php
ob_start();
$file='images';
foreach (glob($file."\*.jpg") as $filenames) {
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
$data = $filenames."\r\n";
fwrite($handle, $data);
}
?>
Hi I need to receive a post data which will be in an xml that is encoded in a base64 format.
I'll be receiving this from a payment gateway. Now all i get is this. My code creates a txt file but is empty. Is there anything wrong with the code? The output should be an xml envelope in a text file.
$body = '';
$fh = #fopen('php://input', 'r');
if ($fh)
{
while (!feof($fh))
{
$s = fread($fh, 1024);
echo $s;
if (is_string($s))
{
$body .= $s;
}
}
fclose($fh);
}
$body = base64_decode($body);
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $body;
fwrite($fh, $stringData);
fclose($fh);
I tried to contact the payment gateway and they are telling me that they are getting this error "The remote server returned an error: (417) Expectation failed." where could the problem exist us or them?
Since your file is returning blank, I would recommend verifying the specifications from the payment gateway for your fopen() function. In addition, if you are properly getting data back from them, then I would check the base64_decode() function. I have seen situations where there may be a header or other data at the top of the actual payload data that fouls up the base64_decode and ruins your day.
It looks like you are mixing up your file handlers, can you see if the following codes run:
$body = $HTTP_RAW_POST_DATA;
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
$stringData = $body;
fwrite($ourFileHandle, $stringData);
fclose($ourFileHandle);
I have just tested the above code myself successfully.
What I suggest you do is trying the following:
Try to put a static piece of data into $body (eg: "$body = 'test';")- and see if that saves - if not then it is an issue at your end.
Delete the file (to remove any permission issues).
Double check the url that the payment gateway is sending to is correct.
Does the php's echo wait to send data to the screen, until the rest of the script is complete?
So if I have:
<?
echo "Hello World";
$xmlData = file_get_cotents("www.webpage.com");
$myFile = "data_backup.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $xmlData;
fwrite($fh, $stringData);
fclose($fh);
?>
So does the above sample what to show Hello World until the contents from the url are retrived and saved locally?
Yep. unless you flush the data with flush();
All of the scripting in PHP occurs before the page loads, so the answer to your question is: yes, it would wait until the file is retrieved and saved before showing "Hello World".
I may be over thinking this but are there any extra steps I am missing after reading my XML data into a string and before writing it to a local file?
header('Content-type: text/xml');
//MY URL TO A XML PAGE STYLED WITH XML STYLE SHEET
$url = "http://www.mywebsite.com/somexmlfile.xml";
//SAVE CONTENTS OF PAGE IN XML_DATA
$xml_data = file_get_contents($url);
//REMOVE STYLE SHEET INFO
$search2 = '<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>';
$xml_data = str_replace( $search2, "", $xml_data);
//WRITE MY DATA TO A BACKUP FILE AND THEN ECHO TO THE SCREEN FOR A FLASH APP CALLING THE INFO
$myFile = "data_backup.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $xml_data;
fwrite($fh, $stringData);
fclose($fh);
echo $xml_data;
The reason I ask this is when I try opening my backup XML file in Dreamweaver it crashes everytime. I was thinking there could be an encoding issue possible.
Task: Cut or erase a file after first walk-through.
i have an install file called "index.php" which creates another php file.
<?
/* here some code*/
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "<?php \n
echo 'hallo, *very very long text*'; \n
?>";
fwrite($fh, $stringData);
/*herecut"/
/*here some code */
after the creation of the new file this file is called and i intent to erase the
filecreation call since it is very long and only needed on first install.
i therefor add to the above code
echo 'hallo, *very very long text*'; \n
***$new= file_get_contents('index.php'); \n
$findme = 'habanot';
$pos = strpos($new, $findme);
if ($pos === false) {
$marker='herecut';\n
$new=strstr($new,$marker);\n
$new='<?php \n /*habanot*/\n'.$new;\n
$fh = fopen('index.php', 'w') or die 'cant open file');
$stringData = $new;
fwrite($fh, $stringData);
fclose($fh);***
?>";
fwrite($fh, $stringData);]}
Isnt there an easier way or a function to modify the current file or even "self destroy" a file after first call?
Regards
EDIT: found the way to edit, sorry to zaf
unlink(__FILE__);
can be used to delete the "helper file" after execution.
unlink(__FILE__);
for the "helper" file seems necessary since i cant find a way to modify the php-file inuse/process.
Most self-installing PHP sites use an install.php to perform the initial set-up. When the install is verified, you would redirect to removeinstall.php which would call unlink() on each installation file to clear them all out.
This does leave behind the removeinstall.php, but has the benefit of not polluting any of the "live code" with installation removal code.
removeinstall.php would simply contain the unlink statements...
if (file_exists('install.php')) {
unlink('install.php');
}
If you don't want to leave behind the removeinstall.php, you could have a conditional call in a different file... for example index.php?removeinstallation=1 or similar.