Reading line breaks from .txt file in PHP - php

I'm trying to read a txt file using PHP and then echo the contents of that text file out into JSON format to send back via an AJAX request. This works fine for me when the txt file contains no line-breaks/paragraphs, but not when there is.
Therefore I'm looking for a way to search for line breaks within the text file when it's contents is returned and replace them with a < br > tag to insert into the JSON.
Currently my code looks like this...
$jsonFile = '{';
$projectName = $_POST["project"];
//directories
$videoDir = $_SERVER['DOCUMENT_ROOT'].'/malagnini/projects/'.$projectName.'/video/';
$audioDir = $_SERVER['DOCUMENT_ROOT'].'/malagnini/projects/'.$projectName.'/audio/';
$textData = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/malagnini/projects/'.$projectName.'/description.txt', true);
//add text data to JSON
$jsonFile .= '"text":"'.$textData.'",';
//add video paths to JSON
$j = 1;
if ($dirHandle = opendir($videoDir) ){
while (($file = readdir($dirHandle)) !== FALSE){
if (!is_dir($file)){
$jsonFile .= '"video'.$j.'":"'.$file.'",';
$j++;
}
}
};
//add audio paths to JSON
$jsonFile .= '"audio": {';
$i = 1;
if ($dirHandle = opendir($audioDir) ){
while (($track = readdir($dirHandle)) !== FALSE){
if (!is_dir($track)){
$jsonFile .= '"track'.$i.'":"'.$track.'",';
$i++;
}
}
};
//echo JSON
$jsonFile = chop($jsonFile, ",");
$jsonFile .= '} }';
echo $jsonFile;
So the text data is read in through the var &textData, but when it outputs to JSON it is not valid JSON when there are line breaks in the txt file.

Therefore I'm looking for a way to search for line breaks within the
text file when it's contents is returned and replace them with a < br > tag to insert into the JSON.
I think this is what you need :
http://php.net/manual/fr/function.nl2br.php

you shouldn't compile json manually, why not build an array with the desired properties and then json_encode it?
Therefore you wouldn't have to bother at all about the inner composition of the strings.

Easiest way to convert newline character to break tag, is to simply run the string through nl2br()

Related

how can I get the image names that are inside a text file with php?

Like always, I am having issues doing this. So, I have been able to extract images from folders using php, but since it was taking too long to do that, I decided to just extract the names from a text file and then do a while loop and echo the list of results. For example I have a file called, "cats.txt" and inside the data looks like this.
Kitten1.jpg
Kitten2.jpg
Kitten3.jpg
I could easily use an sql or json table to do this, but I am not allowed. So, I only have this.
Now, I have tried doing this, but I get an error.
--- PHP CODE ---
$data = file ("path/to/the/file/cats.txt");
for ($i = 0; $i < count ($data); i++){
$images = '<img src="/kittens/t/$i">';
}
$CatLife = '
Images of our kittens:<br>
'.$images.'
';
I would really appreciate the help. I am not sure of what the error is, since the page doesn't tell me anything. It just doesn't load.
You can try something like this:
$fp = fopen('path/to/the/file/cats.txt', 'r');
$images = '';
while(!feof($fp)) {
$row = fgets($fp);
$images .= '<img src="/kittens/t/'.$row.'">';
}
fclose($fp);
$CatLife = "Images of our kittens:<br>$images";
Maybe you should use the glob php function instead of parsing your txt file.
foreach (glob("path/to/the/file/Kitten*.jpg") as $filename) {
echo "$filename\n";
}
Get used to foreach(). Much easier. Also note that variables like $file in your img tag don't get interpreted in single quotes. I use an array and then implode it:
$data = file ("path/to/the/file/cats.txt");
foreach($data as $file) {
$images[] = '<img src="/kittens/t/'.$file.'">';
}
$CatLife = '
Images of our kittens:<br>
'.implode($images).'
';
You could also just use $images .= '<img src="/kittens/t/$file">'; to concatenate and not need to implode.
$data = file ("path/to/the/file/cats.txt");
$images = '';
for ($i = 0; $i < count ($data); i++){
$images .= '<img src="/kittens/t/$i">');
}
$CatLife = 'Images of our kittens:<br>'.$images.'';
echo $CatLife;
Try this, it stores each image tag into a string and echos it to the page.

how can I sort a text file in php

english, lang1, lang2
rat, rat_lang1, rat_lang2
ball, ball_lang1, ball_lang2
air, air_lang1, air_lang2
If I have this text file I read in php, how can I sort it starting the second line, the first line being the heading of the file. So that the file will print out like..
english....
air....
ball...
rat....
I read the file using fopen, put it in $content using fread, used explode with new line. I can see the array of lines but cannot figure out how to sort it. Any suggestions would be appreciated.
Much of this solution was answered within the comments in response to your question. All put together you're looking for something like:
<?php
$f = file("text.txt"); //read the text file into an array
$newf = fopen("newtext.txt", "w+"); //open another file
$header = $f[0]; //store the first element of the array as $header
echo $header."<br>"; //and echo the header
fwrite($newf, $header); //write the header to the new file
array_shift($f); //then remove the first element of the array i.e. the header
sort($f); //sort the array (no flag param = alphabetical sort)
foreach($f as $line){ //loop through the sorted array
echo $line."<br>"; //print each element as it's own line
fwrite($newf, trim($line)."\n"); //write other elements to new file on own line
}
fclose($newf); //close the file
?>
Try this:
$data = trim(file_get_contents('sort_test.txt'));
$data = explode("\n", $data);
$array_order = array();
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation, "w");
for ($i = 0; $i < count($data); $i++) {
($i > 0) ? $array_order[$i] = $data[$i] : fwrite($file, $data[0]);
}
sort($array_order);
$data = implode("\n", $array_order);
fwrite($file, $data);
fclose($file);
echo 'file created - location::' . $fileLocation;
Output myfile.txt
english, lang1, lang2
air, air_lang1, air_lang2
ball, ball_lang1, ball_lang2
rat, rat_lang1, rat_lang2
Maybe the new file (myfile.txt) will needs write permission to the directory you are writing to , in my case the file has been stored into C:/.../htdocs/myfile.txt

How to read a csv file with php code inside?

i searched Google but found nothing what fits for my problem, or i search with the wrong words.
In many threads i read, the smarty Template was the solution, but i dont wont use smarty because its to big for this little project.
My problem:
I got a CSV file, this file contents only HTML and PHP code, its a simple html template document the phpcode i use for generating dynamic imagelinks for example.
I want to read in this file (that works) but how can i handle the phpcode inside this file, because the phpcode shown up as they are. All variables i use in the CSV file still works and right.
Short Version
how to handle, print or echo phpcode in a CSV file.
thanks a lot,
and sorry for my Bad english
Formatting your comment above you have the following code:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
echo $zeile;
}
fclose($userdatei);
// so i read in the csv file and the content of csv file one line:
// src="<?php echo $bild1; ?>" ></a>
This is assuming $bild1 is defined somewhere else, but try using these functions in your while loop to parse and output your html/php:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
outputResults($zeile);
}
fclose($userdatei);
//-- $delims contains the delimiters for your $string. For example, you could use <?php and ?> instead of <?php and ?>
function parseString($string, $delims) {
$result = array();
//-- init delimiter vars
if (empty($delims)) {
$delims = array('<?php', '?>');
}
$start = $delims[0];
$end = $delims[1];
//-- where our delimiters start/end
$php_start = strpos($string, $start);
$php_end = strpos($string, $end) + strlen($end);
//-- where our php CODE starts/ends
$php_code_start = $php_start + strlen($start);
$php_code_end = strpos($string, $end);
//-- the non-php content before/after the php delimiters
$pre = substr($string, 0, $php_start);
$post = substr($string, $php_end);
$code_end = $php_code_end - $php_code_start;
$code = substr($string, $php_code_start, $code_end);
$result['pre'] = $pre;
$result['post'] = $post;
$result['code'] = $code;
return $result;
}
function outputResults($string) {
$result = parseString($string);
print $result['pre'];
eval($result['code']);
print $result['post'];
}
Having PHP code inside a CSV file that should be parsed and probably executed using eval sounds pretty dangerous to me.
If I get you right you just want to have dynamic parameters in your CSV file right? If thats the case and you don't want to implement an entire templating language ( like Mustache, Twig or Smarty ) into your application you could do a simple search and replace thing.
$string = "<img alt='{{myImageAlt}}' src='{{myImage}}' />";
$parameters = [
'myImageAlt' => 'company logo',
'myImage' => 'assets/images/logo.png'
];
foreach( $parameters as $key => $value )
{
$string = str_replace( '{{'.$key.'}}', $value, $string );
}

PHP convert JSON object to string

I am making a quiz script. I want a "teacher" to be able to edit the questions. Originally, I tried to use mySQL but it was a bit difficult, so I decided to switch to a JSON file.
After doing some basic checks with PHP, I wrote this block of code
$json = array();
for ($x=1; $x < $count + 1; $x++) {
$q_and_a = array(
"Question" => $_POST["q".$x],
"Answer" => $_POST["a".$x]
);
array_push($json, $q_and_a);
}
$encoded_array = json_encode($json);
// Delete JSON file, create new one and push encoded array into file
$json_file = 'questions.json';
unlink($json_file);
$handle = fopen($json_file, 'w') or die('Cannot open file: '.$json_file);
fwrite($handle, $json_string) or die('Internal Sever Error');
After I got an internal server error, I realized that this is because the $json variable is an array; I need to convert it into a string and then insert it into the file. I first used serialize() but that just inserted some weird stuff into my file. How do I convert the json array into a string before moving it into the file?
Thanks In Advance
Try this piece of code. It doen't use JSON but it still saves data into a file which is split up using tab
<?php
$count=10;//whatever you defined it to
$qa = "";
for ($x=1; $x < $count + 1; $x++) {
$qa .= $_POST["q".$x]."\t".$_POST["a".$x]."\n";
}
$json_file = 'file.txt';
unlink($json_file);
file_put_contents($qa);
?>
<?php
//to retrieve q&a
$qas = file('file.txt',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$qas = explode("\t",$qas);
foreach($qas as $question => $answer)
{
//your code
}
?>
fwrite($handle, $encoded_array) or die('Internal Sever Error');

How can I remove empty paragraphs from an HTML file using simple_html_dom.php?

I want to remove empty paragraphs from an HTML document using simple_html_dom.php. I know how to do it using the DOMDocument class, but, because the HTML files I work with are prepared in MS Word, the DOMDocument's loadHTMLFile() function gives this exception "Namespaces are not defined".
This is the code I use with the DOMDocument object for HTML files not prepared in MS Word:
<?php
/* Using the DOMDocument class */
/* Create a new DOMDocument object. */
$html = new DOMDocument("1.0", "UTF-8");
/* Load HTML code from an HTML file into the DOMDocument. */
$html->loadHTMLFile("HTML File With Empty Paragraphs.html");
/* Assign all the <p> elements into the $pars DOMNodeList object. */
$pars = $html->getElementsByTagName("p");
echo "The initial number of paragraphs is " . $pars->length . ".<br />";
/* The trim() function is used to remove leading and trailing spaces as well as
* newline characters. */
for ($i = 0; $i < $pars->length; $i++){
if (trim($pars->item($i)->textContent) == ""){
$pars->item($i)->parentNode->removeChild($pars->item($i));
$i--;
}
}
echo "The final number of paragraphs is " . $pars->length . ".<br />";
// Write the HTML code back into an HTML file.
$html->saveHTMLFile("HTML File WithOut Empty Paragraphs.html");
?>
This is the code I use with the simple_html_dom.php module for HTML files prepared in MS Word:
<?php
/* Using simple_html_dom.php */
include("simple_html_dom.php");
$html = file_get_html("HTML File With Empty Paragraphs.html");
$pars = $html->find("p");
for ($i = 0; $i < count($pars); $i++) {
if (trim($pars[$i]->plaintext) == "") {
unset($pars[$i]);
$i--;
}
}
$html->save("HTML File without Empty Paragraphs.html");
?>
It is almost the same, except that that the $pars variable is a DOMNodeList when using DOMDocument and an array when using simple_html_dom.php. But this code does not work. First it runs for two minutes and then reports these errors: "Undefined offset: 1" and "Trying to get property of nonobject" for this line: "if (trim($pars[$i]->plaintext) == "") {".
Does anyone know how I can fix this?
Thank you.
I also asked on php devnetwork.
Looking at the documentation for Simple HTML DOM Parser, I think this should do the trick:
include('simple_html_dom.php');
$html = file_get_html('HTML File With Empty Paragraphs.html');
$pars = $html->find('p');
foreach($pars as $par)
{
if(trim($par->plaintext) == '')
{
// Remove an element, set it's outertext as an empty string
$par->outertext = '';
}
}
$html->save('HTML File without Empty Paragraphs.html');
I did a quick test and this works for me:
include('simple_html_dom.php');
$html = str_get_html('<html><body><h1>Test</h1><p></p><p>Test</p></body></html>');
$pars = $html->find("p");
foreach($pars as $par)
{
if(trim($par->plaintext) == '')
{
$par->outertext = '';
}
}
echo $html;
// Output: <html><body><h1>Test</h1><p>Test</p></body></html>
Empty paragraphs looks like <p [attributes]> [spaces or newlines] </p> (case-insensitive). You can use preg_replace (or str_replace) for removing empty paragraphs.
The following will only work if an empty paragraph is <p></p>:
$oldHtml = file_get_contents('File With Empty Paragraphs.html');
$newHtml = str_replace('<p></p>', '', $oldHtml);
// and write the new HTML to the file
$fh = fopen('File Without Empty Paragraphs.html', 'w');
fwrite($fh, $newHtml);
fclose($fh);
This will also work on paragraphs with attributes, like <p class="msoNormal"> </p>:
$oldHtml = file_get_contents('File With Empty Paragraphs.html');
$newHtml = preg_replace('#<p[^>]*>\s*</p>#i', '', $oldHtml);
// and write the new HTML to the file
$fh = fopen('File Without Empty Paragraphs.html', 'w');
fwrite($fh, $newHtml);
fclose($fh);

Categories