从PHP中的.txt文件读取换行符

从PHP中的.txt文件读取换行符

问题描述:

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.

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.

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

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