limitation on writing line to .csv or .txt file php - php

i wrote a convert bulk data from an excel to a .txt or .csv by using fwrite php. however when I fread on the .txt file that my data placed on, the data turned out broken line. how can i fix it? Attached here is the highlighted from .txt or .csv and also the codes as below:-
**********my write code *************
for loop here {
$split_filename_path = fopen($tempfile_path.$split_filename.$total_round.$extension, "w");`
$split_file_txt = $ISBN.$comma.$Title.$comma.$Qty.$comma.$Location.$comma.$outlet;
fwrite($split_filename_path, $split_file_txt);
}
fclose($split_filename_path);
then it comes here
my read code*****
$myfile = fopen($file, "r");
$fread = fread($myfile,filesize($file));
fclose($myfile);
$split = explode("\n",$fread);
$datafields = array('ISBN', 'title', 'qty', 'location', 'outlet');
$insertvalues = array();
foreach($split as $string){
$row = explode(",",$string);
$questionmarks[] = '(' . $this->placeholder('?',$irow, sizeof($row)) . ')';
$insertvalues = array_merge( $insertvalues, array_values($row));
}
$sql = "INSERT INTO temp_data (".implode( ',', $datafields) . ")
VALUES ". implode( ',', $questionmarks);
function placeholder( $text, $irow, $count = 0, $separator = ',' ) {
$result = array();
if ($count > 0) {
for ($x = 0; $x < $count; $x++) {
$result[] = $text;
}
}
return implode($separator, $result);
}
with this codes, the result that I have is here :
9780794435295,BARBIE & HER SISTERS IN THE GREAT PUPPY ADVENTURE: (supposed to be full :- BARBIE & HER SISTERS IN THE GREAT PUPPY ADVENTURE: A SLIDING TAB BOOK BARBIE MOVIE TIEIN )

found the answer.
$Title = preg_replace( "/\r|\n/", "", $Title);

Related

PHP: Insert line break after every $num word in a text file

I want to clean up a .txt file to make it more readable by inserting a line break after every 4th word. The file has been filled with data from an array.
This is what I've come up with so far by looking at this and this:
<?php
require "simple_html_dom.php";
$html = file_get_html("http://www.lipsum.com/");
$data = array();
$counter = 0;
foreach($html->find("div") as $tr){
$row = array();
foreach($tr->find("div") as $td){
$row[] = $td->plaintext;
}
$data[] = $row;
}
ob_start();
var_dump($data);
$data = preg_replace('~((\w+\s){4})~', '$1' . "\n", $data);
file_put_contents('new_text_file.txt', $data);
//$handlefile = fopen("newfile.txt", "w") or die("Unable to open file!");
//file_put_contents('newfile.txt', $data);
//$output = ob_get_clean();
//$outputFile = "newfile.txt";
//fwrite($handlefile, $output);
//fclose($handlefile);
?>
As you can see I've created a for loop and two if statements to "count" the spacing between the words, and when the counter variable has reached 3, a line break is inserted. But it doesn't work since no data from the website is printed to the text file in the first place. It works however, if I remove the for loop and the if statements, without the sorting of course.
Any type of help is appriciated!
Edit: updated code.
Edit 2: final working version. Original question left for further reference.
This is the final working version:
<?php
require "simple_html_dom.php";
$html = file_get_html("http://www.lipsum.com/");
$data = array();
$counter = 0;
foreach($html->find("div") as $tr){
$row = array();
foreach($tr->find("div") as $td){
$row[] = $td->plaintext;
}
$data[] = $row;
}
ob_start();
var_dump($data);
$handlefile = fopen("newfile.txt", "w") or die("Unable to open file!");
file_put_contents('newfile.txt', $data);
$output = ob_get_clean();
$outputFile = "newfile.txt";
fwrite($handlefile, $output);
fclose($handlefile);
function MakeFileReadable($source , $export) {
$content = file_get_contents($source);
$x = explode (" " , $content);
$newx = "";
$count = 1;
foreach ($x as $word) {
$newx .= $word . " ";
if ($count %12 ==0) $newx .= "\r\n";
$count ++;
}
$fp = fopen("file-export.txt" , 'w');
if (!$fp) die("There is a problem with opening file...");
fwrite($fp , $newx);
fclose($fp);
}
MakeFileReadable("newfile.txt" , "file-export.txt");
?>
Use some array functions
$string = "one two three four five six seven eight nine ten eleven tweleve thirteen fourteen";
$arr = explode (" " , $string);
$lines = array_chunk($arr,4);
foreach($lines as $line)
echo implode (" ", $line)."\r\n";
result
one two three four
five six seven eight
nine ten eleven tweleve
thirteen fourteen
Here's a regex solution.
<?php
$test = 'one two three four five six seven eight nine ten eleven tweleve thirteen fourteen';
echo preg_replace('~((\w+\s){4})~', '$1' . "\n", $test);
Output:
one two three four
five six seven eight
nine ten eleven tweleve
\w is a word character (Alphanumeric characters plus "_", http://en.wikipedia.org/wiki/Regular_expression), if you only want A-Z use [a-z] and use the i modifier to make it case insensitive, ~((\w+\s){4})~i. The \s is a whitespace and the {4} is requiring 4 occurrences of the \w+\s.
Per your code...
$data = preg_replace('~((\w+\s){4})~', '$1' . "\n", $data);
file_put_contents('new_text_file.txt', $data);
http://php.net/manual/en/function.file-put-contents.php
Per updated code:
<?php
require "simple_html_dom.php";
$html = file_get_html("http://www.lipsum.com/");
$data = array();
$counter = 0;
foreach($html->find("div") as $tr){
$row = array();
foreach($tr->find("div") as $td){
$row[] = $td->plaintext;
}
$data[] = $row;
}
$data = preg_replace('~((\w+\s){4})~', '$1' . "\n", implode(' ', $data));
file_put_contents('new_text_file.txt', $data, FILE_APPEND | LOCK_EX);
Finally tested code:
<?php
function MakeFileReadable($source , $export) {
$content = file_get_contents($source);
$x = explode (" " , $content);
sort($x);
$newx = "";
$count = 1;
foreach ($x as $word) {
$newx .= $word . " ";
if ($count %4 ==0) $newx .= "\r\n";
$count ++;
}
$fp = fopen($export , 'w');
if (!$fp) die("There is a problem with opening file...");
fwrite($fp , $newx);
fclose($fp);
}
MakeFileReadable("file-input.txt" , "file-export.txt");

Saving hex data in binary using PHP does not work properly

I am learning PHP and files and I am trying to write some code that put data in a binary file.
here's my code:
Write
<?php
echo "\n\nWRITE: \n\n";
$c = array();
$data = '';
$c['name'] = 'abcdefghijklmnopqrstuvwxyz';
$data .= implode('', $c);
$fp = fopen('test.bin', 'wb');
$len = strlen($data);
echo "\nFILE CONTENT: $data (strlen: $len)\n\n";
for ($i = 0; $i < $len; ++$i) {
$hx = dechex(ord($data{$i}));
fwrite($fp, pack("C", $hx));
}
echo "Last char is: $hx which mean: ";
echo chr(hexdec('7a'));
echo "\n--------------------------------------------\n";
fclose($fp);
Output
FILE CONTENT: abcdefghijklmnopqrstuvwxyz (strlen: 26)
Last char is: 7a which mean: z
Read
<?php
echo "\n--------------------------------------------\n";
echo "\n\nREAD: \n\n";
$fp = fopen('test.bin', 'rb');
$fseek = fseek($fp, 0, SEEK_SET);
if($fseek == -1) {
return FALSE;
}
$data = fread($fp, 26);
$arr = unpack("C*", $data);
$return = '';
foreach($arr as $val) {
$return .= chr(hexdec($val));
}
$n = '';
$arr = array();
$arr['name'] = substr($return, 0, 26);
print_r($arr);
echo "\n--------------------------------------------\n";
Output
Array
(
[name] => abcdefghipqrstuvwxy
)
Where are the missing letters like the z, m, n or o ?
EDIT 6-3-14 7h36 am: I would like to have the .bin file not plain text if possible
You are trying to set HEX chars in a char (C - unsigned char) instruction.
echo "\t";
foreach( array('0x41', 65, 'a') as $o )
echo $o."\t";
echo "\n";
foreach( array('c*','C*','a*','A*','h*','H*','v*','n*','S*') as $o ){
echo $o . "\t";
foreach( array(0x41, 65, "a") as $oo ) {
echo pack($o, $oo);
echo "\t";
}
echo "\n";
}
If you run this, you will see quickly how pack works with the 3 different values of a (HEX, DEC and normal).
You have to use the h instruction to accomplish what you need.
function writeToFile($data) {
$fp = fopen(FILENAME, 'wb');
$len = strlen($data);
for ($i = 0; $i < $len; ++$i) {
$hx = dechex(ord($data[$i]));
$result = fwrite($fp, pack("h*", $hx));
if(!$result) {
// show something
}
}
fclose($fp);
}
Now, for read that data. You will need to use the same one h and split the string you get back (split it using str_split with the parameter 2 since it's HEX 00 = 0 and FF = 255 - assuming you won't go over 255). Since h returns an array with a single element. Once you get your string back, you need to convert the number you get from the ord in the writeToFile using the chr function.
function readFromFile($lenght, $pos = 0) {
$return = '';
$fp = fopen(FILENAME, 'rb');
if(!$fp) {
// show something
}
$fseek = fseek($fp, $pos, SEEK_SET);
if($fseek == -1) {
// show something
}
$data = fread($fp, $lenght);
$data = unpack("h*", $data);
$arr = str_split(current($data), 2);
foreach($arr as $val) {
$return .= chr(hexdec($val));
}
return $return;
}
Now, you create your string and write to the file:
$data = 'This should work properly, thanks for StackOverFlow!';
$len = strlen($data);
writeToFile($data);
Then read back:
echo readFromFile($len);
The content of your file will look like this:
E<86><96>7^B7<86>öWÆF^Bwö'¶^B^G'ö^GV'Æ<97>Â^BG<86>^Væ¶7^Bfö'^B5G^V6¶ôgV'dÆöw^R

Add newline to center length position of text file lines

input.txt
just some example text, just some example text
some example text
example text, just some example text
$inFile = "input.txt";
$outFile = "output.txt";
$data = array();
$ftm = fopen($outFile, "w+");
$fh = fopen($inFile, "r");
$data = file($inFile);
foreach ($data as $key => $value)
{
$row = $value;
$str_length = strlen($row);
if ($str_length > 10)
{
$width = strlen($row)/2;
$wrapped = wordwrap($row, $width);
fwrite($ftm, $wrapped);
}
else
{
fwrite($ftm, $row);
}
}
fclose($fh);
How can I add a newline \n to the center position of each line?
//Related:
$wrapped = wordwrap($row, $width, '\N');
I'm not sure if this is what you're expecting, but it works given supplied text:
just some example text
some example text
example text
which results to a written file as: (if using '\n')
just some\nexample\ntext
some\nexample\ntext
example\ntext
(EDIT) and as:
just some
example
text
some
example
text
example
text
(if using "\n") which will result having no spaces at the end of each line.
PHP
<?php
$inFile = "input.txt";
$outFile = "output.txt";
$data = array();
$ftm = fopen($outFile, "w+");
$fh = fopen($inFile, "r");
$data = file($inFile);
foreach ($data as $key => $value)
{
$newline = "\n"; // writes to file with no spaces at the end of each line
// $newline = '\n'; // use single quotes if wanting to write \n in the file
$row = $value;
$str_length = strlen($row);
if ($str_length > 10)
{
$width = strlen($row) / 2;
$wrapped = wordwrap($row, $width, $newline);
fwrite($ftm, $wrapped);
}
else
{
fwrite($ftm, $row);
}
}
fclose($fh);

Read line for first top 10 lines and display word in each line of 10 lines using PHP

I have the PHP code as below:
<?php
$path = "files/stats_pmta.affinitead.net.2012-12-12.txt";
$num = 10;
$fh = #fopen($path, 'r');
if ($fh){
for ($i=0;$i<$num;$i++){
$newfile = fgets($fh,1024);
$t = explode(";", $newfile);
echo $t;
echo "<br>";
}
} else {
echo 1;
}
?>
I want to read all data in file stats_pmta.affinitead.net.2012-12-12.txt that read only first 10 lines of the file below:
2012-12-12-0551;affinitead.net;1221588;106346;8.70;gmail.com;123577;7780;6.29
2012-12-12-0551;affinitead.net;1221588;106346;8.70;wanadoo.fr;123562;9227;7.46
2012-12-12-0551;affinitead.net;1221588;106346;8.70;yahoo.fr;104819;1685;1.60
2012-12-12-0551;affinitead.net;1221588;106346;8.70;orange.fr;87132;7341;8.42
2012-12-12-0551;affinitead.net;1221588;106346;8.70;laposte.net;79597;1040;1.30
2012-12-12-0551;affinitead.net;1221588;106346;8.70;hotmail.fr;77601;14107;18.17
2012-12-12-0551;affinitead.net;1221588;106346;8.70;neuf.fr;67392;1793;2.66
2012-12-12-0551;affinitead.net;1221588;106346;8.70;hotmail.com;55300;10494;18.97
2012-12-12-0551;affinitead.net;1221588;106346;8.70;free.fr;43422;1706;3.92
2012-12-12-0551;affinitead.net;1221588;106346;8.70;sfr.fr;39063;251;.64
2012-12-12-0551;affinitead.net;1221588;106346;8.70;aol.com;32061;9859;30.75
2012-12-12-0551;affinitead.net;1221588;106346;8.70;club-internet.fr;22424;233;1.03
2012-12-12-0551;affinitead.net;1221588;106346;8.70;yahoo.com;18646;1365;7.32
2012-12-12-0551;affinitead.net;1221588;106346;8.70;voila.fr;18513;3650
After I read first top 10 lines I want to display the word in each line like:
2012-12-12-0551;affinitead.net;1221588;106346;8.70;gmail.com;123577;7780;6.29
I want to display gmail.com 123577 7780 6.29
But PHP code above I just got the output array.I don't know how to fix this.Anyone help me please , Thanks.
You could do something like this:
$path = 'path/to/file'
$fp = fopen($path, 'r');
$count = 0;
while($columns = fgetcsv($fp, 256, ';', '"')
{
if(++$count > 10)
break;
echo implode("\t", $colums);
}
If you don't know, how implode works, look here: http://de1.php.net/manual/de/function.implode.php
This is a way you could do it by using the PHP-function explode.
$textFile = file_get_contents("test.txt");
$lineFromText = explode("\n", $textFile);
$row = 0;
foreach($lineFromText as $line)
{
if($row <= 10)
{
$words = explode(";",$line);
echo $words[5] . ' ' . $words[6] . ' ' . $words[7] . ' ' . $words[8];
$row++;
}
}
Edited the code so that you can replace your own, you might want to check if the file is empty e t c before trying to do anyting thou.

PHP - parsing a txt file

I have a .txt file that has the following details:
ID^NAME^DESCRIPTION^IMAGES
123^test^Some text goes here^image_1.jpg,image_2.jpg
133^hello^some other test^image_3456.jpg,image_89.jpg
What I'd like to do, is parse this ad get the values into a more readable format, possibly into an array if possible.
Thanks
You can do that easily this way
$txt_file = file_get_contents('path/to/file.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
foreach($rows as $row => $data)
{
//get row data
$row_data = explode('^', $data);
$info[$row]['id'] = $row_data[0];
$info[$row]['name'] = $row_data[1];
$info[$row]['description'] = $row_data[2];
$info[$row]['images'] = $row_data[3];
//display data
echo 'Row ' . $row . ' ID: ' . $info[$row]['id'] . '<br />';
echo 'Row ' . $row . ' NAME: ' . $info[$row]['name'] . '<br />';
echo 'Row ' . $row . ' DESCRIPTION: ' . $info[$row]['description'] . '<br />';
echo 'Row ' . $row . ' IMAGES:<br />';
//display images
$row_images = explode(',', $info[$row]['images']);
foreach($row_images as $row_image)
{
echo ' - ' . $row_image . '<br />';
}
echo '<br />';
}
First you open the text file using the function file_get_contents() and then you cut the string on the newline characters using the function explode(). This way you will obtain an array with all rows seperated. Then with the function array_shift() you can remove the first row, as it is the header.
After obtaining the rows, you can loop through the array and put all information in a new array called $info. You will then be able to obtain information per row, starting at row zero. So for example $info[0]['description'] would be Some text goes here.
If you want to put the images in an array too, you could use explode() too. Just use this for the first row: $first_row_images = explode(',', $info[0]['images']);
Use explode() or fgetcsv():
$values = explode('^', $string);
Or, if you want something nicer:
$data = array();
$firstLine = true;
foreach(explode("\n", $string) as $line) {
if($firstLine) { $firstLine = false; continue; } // skip first line
$row = explode('^', $line);
$data[] = array(
'id' => (int)$row[0],
'name' => $row[1],
'description' => $row[2],
'images' => explode(',', $row[3])
);
}
By far the best and simplest example of this I have come accross is quite simply the file() method.
$array = file("myfile");
foreach($array as $line)
{
echo $line;
}
This will display all the lines in the file, this is also applicable for a remote URL.
Simple and clear.
REF : IBM PHP Parse
I would like to contribute a file that provides atomic data structures.
$lines = file('some.txt');
$keys = explode('^', array_shift($lines));
$results = array_map(
function($x) use ($keys){
return array_combine($keys, explode('^', trim($x)));
},
$lines
);
Try fgetcsv() with ^ as the separator character:
$file = fopen($txt_file,"r");
print_r(fgetcsv($file, '^'));
fclose($file);
http://www.w3schools.com/php/func_filesystem_fgetcsv.asp
<?php
$row = 1;
if (($handle = fopen("test.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "^")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
Ok, didn't see the edited version, so here's a redo. It's most likely a CSV file that uses carets as the separator, so...
$fh = fopen('yourfile.txt');
$headers = fgetcsv($fh, 0, '^');
$details = array();
while($line = fgetcsv($fh, 0, '^')) {
$details[] = $line;
}
fclose($fh);
youse a list, and split the "image_1.jpg,image_2.jpg" after you explode the string:
list($number, $status, $text, $images) = explode("^", $data);
$splited_images= preg_split(',', $images);
My solution
function parseTextFile($file){
if( !$file = file_get_contents($file))
throw new Exception('No file was found!!');
$data = [];
$firstLine = true;
foreach(explode("\n", $file) as $line) {
if($firstLine) {
$keys=explode('^', $line);
$firstLine = false;
continue;
} // skip first line
$texts = explode('^', $line);
$data[] = array_combine($keys,$texts);
}
return $data;
}

Categories