Issue with the text file writing in php - php

I am using urldecode data for writing a content in to a text file, but in that file all the contents are showing together(not aligned expected) in windows notepad(in windows wordpad it is coming correctly), also when i open it in Ubuntu contents are coming correctly(my contents have enter key and spaces some special characters too).
$attachment_file = fopen(Yii::app()->basePath.'/../uploads/attachment'.$user_id.'.txt', "a+") or die("Unable to open file!");
$content = urldecode($note_data["note_data"]);
fwrite($attachment_file,$content);
fclose($attachment_file);
For the quick fix i did
$content = str_replace("\n","\r\n",$content);
but i want to know is there any other methods to do it.

If you are using Linux to create the file, you should manually add this. If you use Windows, You can try str_replace("\n", PHP_EOL, $content) instead.
I don't understand why you are doing urldecode. Maybe you should use something like utf8_decode if you have your data in utf-8 format.

Related

How do I use file_get_contents() when the filename contains a single quote?

I have to read the contents of a file with a single quote (') in the file name. I have no influence on the file name, so renaming is not an option. Unfortunately, simply escaping it doesn't work, as in:
$myFile = 'John\\\'s file';
$text = file_get_contents($myFile);
What would be the correct way to access this file in PHP 5 on a Linux system?
You don't need to double-escape your string:
$myFile = 'John\'s file'; // This works fine.
$text = file_get_contents($myFile);
I've just tried a similar command on my terminal:
php -r "chdir('te\'st');"
It works.

How to convert a CSV file using a PHP script

I need to convert a CSV file to UTF-8 and rename it using a PHP script.
The following code worked on my PC but now i need to do this on a server as a CRON task
iconv -f UTF-16LE -t UTF-8 OLD-FILE.csv > NEW-FILE.csv
Anyone know the equivalent in PHP. Thanks a lot.
A simple method would be to load the CSV file to a string using this command:
http://php.net/manual/en/function.file-get-contents.php
Then you can UTF-8 Encode the string using this command:
http://php.net/manual/en/function.utf8-encode.php
Finally write the string to a file using file_put_contents.
Finished code could look like this:
$file_data = file_get_contents('/my/path/to/file.csv');
$utf8_file_data = utf8_encode($file_data);
$new_file_name = '/my/path/to/new_file.csv';
file_put_contents($new_file_name , $utf8_file_data );
Make sure the web server has the correct permissions to both read and write to appropriate locations.
Here is the link to file_put_contents():
http://php.net/manual/en/function.file-put-contents.php
So here is the solution I found thanks to our brainstorming:
<?php
$file_data = file_get_contents('/home/MYFILE.csv');
//$utf8_file_data = utf8_encode($file_data);
$utf8_file_data = mb_convert_encoding($file_data, "UTF-8", "UTF-16LE");
//$utf8_file_data = iconv("UTF-16LE","UTF-8",$file_data);
$new_file_name = '/home/MYFILE_NEW.csv';
file_put_contents($new_file_name , $utf8_file_data );
?>
The only pb is that the output size is twice as big as the input. If I use ICONV on my PC it is HALF the size...
If anyone knows I'd like to hear why.
if iconv is available you can use the PHP equivalent: http://php.net/manual/en/function.iconv.php note that this takes a string, you will need to read in the file http://php.net/manual/en/function.fread.php and then write it out http://php.net/manual/en/function.file-put-contents.php but this approach may be slower and for big files, it will require to load the file to memory.

Editing a .doc in PHP

I am trying to replace strings in a word document by reading the file into a variable $content and then using str_ireplace() to change the string. I can read the content from the file but I str_ireplace() does not seem to be able to replace the string. I assumed it would because the string is 'binary safe' according to the PHP documentation. Sorry, I am a beginner with PHP file manipulation so all this is quite new to me.
This is what I have written.
copy('jack.doc' , 'newFile.doc');
$handle = fopen('newFile.doc','rb');
$content = '';
while (!feof($handle))
{
$content .= fread($handle, 1);
}
fclose($handle);
$handle = fopen('newFile.doc','wb');
$content = str_ireplace('USING_ICT_BOX', 'YOUR ICT CONTENT', $content);
fwrite($handle, $content);
fclose($handle);
When I download the new file, it opens as it should in MS Word but it shows the old string and not the one that should be replaced.
Can I fix this issue? Is there any better tool I can use for replacing strings in MS Word thourgh PHP?
I have same requirement for Edit .doc or .docx file using php and i have find solution for it.
And i have write post on It :: http://www.onlinecode.org/update-docx-file-using-php/
copy('jack.doc' , 'newFile.doc');
$full_path = 'newFile.doc';
if($zip_val->open($full_path) == true)
{
// In the Open XML Wordprocessing format content is stored.
// In the document.xml file located in the word directory.
$key_file_name = 'word/document.xml';
$message = $zip_val->getFromName($key_file_name);
$timestamp = date('d-M-Y H:i:s');
// this data Replace the placeholders with actual values
$message = str_replace("client_full_name", "onlinecode org", $message);
$message = str_replace("client_email_address", "ingo#onlinecode.org", $message);
$message = str_replace("date_today", $timestamp, $message);
$message = str_replace("client_website", "www.onlinecode.org", $message);
$message = str_replace("client_mobile_number", "+1999999999", $message);
//Replace the content with the new content created above.
$zip_val->addFromString($key_file_name, $message);
$zip_val->close();
}
Maybe this would point you to the right direction: http://davidwalsh.name/read-pdf-doc-file-php
Solutions I've found so far (not tested though):
Docvert - works for Doc, free, but not directly usable
PHPWordLib - works for Doc, not free
PHPDocX - DocX only, needs Zend.
I am going to opt for PHPWord www.phpword.codeplex.com as I believe teachers are going to get Office 2007 next year and also I will try and find some way to convert between .docx and .doc through PHP to support them in the mean time.
If you can reach a web-service, look at Docmosis Cloud services since it can mailmerge a doc file with your data and give you back a doc/pdf/other. You can https post to the service to make the request so is pretty straight forward from PHP.
There is many way to handle word document file on linux
antiword - not much effective as it converts into plain text.
pyODconvert
open-office or liboffice - through UNO
unoconv utility - need to installation permission on server
There is one python script which is most usable for online file conversion but you need to convert those file through command line.
There is no specific and satisfied solution to handle word files by only using php code.
I hunted for a long time to reach at this suggestion.

PHP fputcsv with UTF-8 Problem

I'm trying to allow my clients view some of the MySQL data in Excel. I have used PHP's fputcsv() function, like:
public function generate() {
setlocale(LC_ALL, 'ko_KR.UTF8');
$this->filename = date("YmdHis");
$create = $this->directory."Report".$this->filename.".csv";
$f = fopen("$create","w") or die("can't open file");
fwrite($f, "\xEF\xBB\xBF");
$i = 1;
$length = count($this->inputarray[0]);
fwrite($f, $this->headers."\n");
// print column titles
foreach($this->inputarray[0] as $key=>$value) {
$delimiter = ($i == $length) ? "\n\n" : ",";
fwrite($f, $key.$delimiter);
$i++;
}
// print actual rows
foreach($this->inputarray as $row) {
fputcsv($f, $row);
}
fclose($f);
}
My clients are Korean, and a good chunk of the MySQL database contains values in utf8_unicode_ci. By using the above function, I successfully generated a CSV file with correctly encoded data that opens fine in Excel on my machine (Win7 in English), but when I opened the file in Excel on the client computer (Win7 in Korean), the characters were broken again. I tried taking the header (\xEF\xBB\xBF) out, and commenting out the setlocale, to no avail.
Can you help me figure this out?
If, as you say, your CSV file has "correctly encoded data" - i.e. that it contains a valid UTF-8 byte stream, and assuming that the byte stream of the file on your client's site is the same (e.g. has not been corrupted in transit by a file transfer problem) then it sounds like the issue Excel on the client's machine not correctly interpreting the UTF-8. This might be because it's not supported or that some option needs to be selected when importing to indicate the encoding. As such, you might try producing your file in a different encoding (using mb_convert_encoding or iconv).
If you get your client to export a CSV containing Korean characters then you'll be able to take a look at that file and determine the encoding that is being produced. You should then try using that encoding.
Try encoding the data as UTF-16LE, and ensure that the file has the appropriate BOM.
Alternatively, send your clients an Excel file rather than a CSV, then the encoding shouldn't be a problem
Try wrapping the text in each fwrite call with utf8_encode.
Then use what is suggested here: http://www.php.net/manual/en/function.fwrite.php#69566

PHP New Line will not work

Hi I am trying to create some code that first reads the existing contents of the file in and then adds the new line of code on a new line but the code i am using just adds it on the new text on to the already existing line instead of the new line...
Here is the code i am using:
<?php
$id = $_GET['id'];
$userfile = "user1.txt";
$fo = fopen($userfile, 'r') or die("can't open favourites file");
$currentdata = fread($fo, filesize($userfile));
fclose($fo);
$fw = fopen($userfile, 'w') or die("can't open favourites file");
$currentprocessed = "$currentdata\n";
fwrite($fw, $currentprocessed);
fwrite($fw, $id);
fclose($fw);
?>
I have tried a whole range of different ideas but nothing has worked, any help would be appreciated.
Line endings per OS
Unix / Linux
\n
DOS / Windows
\r\n
Invalid
\r and \n\r
The value of PHP_EOL constant depends on the platform php is running on.
It doesn't detect the line-endings in the current file or anything magic.
Instead of appending \n, concatenate the constant PHP_EOL which is always the correct newline character for the current platform.
It might also be an issue with the program you're using to open the text file with. For instance, Notepad on Windows is incapable of understanding unix style newlines.
I ran into this same issue. What application are you using to read the file? I found that for some reason Notepad (my default for .txt files) didn't recognize the "\n\r" escape characters. I opened my .txt file that I was writing to using Notepad++, Atom (my text editor of choice), or in a browser and they all showed the line breaks just fine.

Categories