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");
?>
Finally tested code: