encoding from .txt file to string using php - php

I'm doing this project where I receive a .txt file from a MATLAB program in a PHP server. I would like to extract the data in the .txt file and encode it to a string to be sent by the server to an android. Any ideas on how to do that?

Screw the string.
readfile()

use below code for your task.
$file = file_get_contents('test.txt', true);
$parsed_str = json_decode($file);
I think it may be helpful to you..
Thanks.

Related

How to read any of the file type using php7?

I have tried to extract the user email addresses from my server. But the problem is maximum files are .txt but some are CSV files with txt extension. When I am trying to read and extract, I could not able to read the CSV files which with TXT extension. Here is my code:
<?php
$handle = fopen('2.txt', "r");
while(!feof($handle)) {
$string = fgets($handle);
$pattern = '/[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/i';
preg_match_all($pattern, $string, $matches);
foreach($matches[0] as $match)
{
echo $match;
echo '<br><br>';
}
}
?>
I have tried to use this code for that. The program is reading the complete file which are CSV, and line by line which are Text file. There are thousands of file and hence it is difficult to identify.
Kindly, suggest me what I should do to resolve my problem? Is there any solution which can read any format, then it will be awesome.
Well your files are different. Because of that you will have to take a different approach for each of those. In more general terms this is usually calling adapting and is mostly provided using the Adapter design pattern.
Should you use the adapter design pattern you would have a code inspecting the extension of a file to be opened and a switch with either txt or csv. Based on the value you would retrieve aTxtParseror aCsvParser` respectively.
However, before diving deep into this territory you might want to have a look at the files first. I cannot say this for sure without seeing the structures but you can. If the contents of both the text and csv files are the same then a very simple approach is to change the extension to either txt or a csv for all files and then process them using same logic, knowing files with the same extension will now be processed in the same manner.
But from what I understood the file structures actually differ. So to keep your code concise the adapter pattern, having two separate classes/functions for parsing and another one on top of that for choosing the right parsing function (this top function would actually be a form of a strategy) and running it.
Either way, I very much doubt so there is a solution for the problem you are facing as a file structure is mostly your and your own.
Ok, so problem is when CSV file has too long string line. Based on this restriction I suggest you to use example from php.net Here is an example:
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
// do your operation for searching here
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}

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.

Create a file with another languages characters in php

i'm trying to create a file with name "Дискография" but in the folder appears with the name ДиÑкографиÑ.
The php file is in UTF-8.
I'm working on windows.
My file system is NTFS.
i have this:
<?php
$nombre = "Дискография";
$fp = fopen("C:/$nombre", 'w+');
fclose($fp);
?>
Looks like this was addressed somewhat in another answer:
How do I use filesystem functions in PHP, using UTF-8 strings?
Original/old answer:
It probably depends on the coding of your filesystem, but at a guess, I'd use:
$nombre = utf8_encode("Дискография");

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.

How to parse file in php and generate insert statements for mysql?

In case of csv file we have fgetcsv in php to parse and get the output but in my case file is .dat and I need to parse it and store it into MySQL Database and so do we have any built in function in php like fgetcsv that can work in similar fashion on .dat file ?
Here is the sample value, it has headers DF_PARTY_ID;DF_PARTY_CODE;DF_CONNECTION_ID and its value as mentioned under.
Sample Data:
DF_PARTY_ID;DF_PARTY_CODE;DF_CONNECTION_ID
87961526;4002524;13575326
87966204;4007202;13564782
What's wrong with fgetcsv()? The extension on the file is irrelevant as long as the format of the data is consistent across all of your files.
Example:
$fh = fopen('example.dat', 'r');
while (!feof($fh)) {
var_dump(fgetcsv($fh, 0, ';'));
}
Alternatively, with PHP5.3 you can also do:
$lines = file('example.dat');
foreach($lines as $line) {
var_dump(str_getcsv(trim($line), 0, ';'));
}
IMHO .dat files can be of different formats. Blindly following the extension can be error-prone. If however you have a file from some specific application, maybe tell us what this app is. Chances are there are some parsing libraries or routines.
I would imagine it would be easier to write a short function using fopen, fread, and fclose to parse it yourself. Read each line, explode to an array, and store them as you wish.

Categories