io - Writing to Text files via php

597

I have a little issue while trying to kill time. I am writint to a text file the contents of the filled in form so it is easy to read. At the moment everything gets put int a single line, and therfore I can not tell where msgs begin or end. I wrote a php like this:

$from = $_POST[from];
$friend = $_POST[friend];
$carrier = $_POST[carrier];
$message = stripslashes($_POST[message]);

if ((empty($from)) || (empty($friend)) || (empty($message))) {
header ("Location: sms_error.php");
}

else if ($carrier == "orange_mobile_network") {
$formatted_number = $friend."@orange_mobile_network.co.uk";
mail("$formatted_number", "SMS", "$message"); 

header ("Location: sms_success.php");
}

Then the SMS/Text message will be sent. After this I wanted to write/store/append the message on a txt file. So I wrote:

$myFile = "sms_Numbers_Mgs.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");

$stringData = $_POST[from];
fwrite($fh, $stringData);

$stringData = $_POST[friend];
fwrite($fh, $stringData);

$stringData = $_POST[message];
fwrite($fh, $stringData);

fclose($fh);

But like I said. Everything works. I just want to be able to read the file and put everything in a new line and possibly format it nicely for easy reading. I do not want to use a DB for storing the TXT as my host is going to charge me.

702

Answer

Solution:

change this:

fwrite($fh, $stringData);

with this:

fwrite($fh, $stringData . PHP_EOL);

or:

fwrite($fh, $stringData . "\r\n");
422

Answer

Solution:

You can appendPHP_EOL when you write for a platform aware newline. I.e.$stringData = <string> . PHP_EOL;

If don't need it to be platform aware, going with the windows newline is a safe option.

define('CRLF', "\r\n");

$stringData = <string> . CRLF;
fwrite($fh, $stringData);
819

Answer

Solution:

I do not know exactly Cause you're using. txt instead of a bank, but my tip for this specific case is to work with json format.

Example:

$myFile = "sms_Numbers_Mgs.txt";

$fh = fopen($myFile, 'a+') or die("can't open file");

//assembles a string of type json
$data = json_encode(array(
    'from'    => $_POST[from],
    'friend'  => $_POST[friend],
    'message' => $_POST[message]
));

//Write in the file
fwrite($fh, $data);
fclose($fh);

//reads the file
$content = file_get_contents($myFile);
$object  = json_decode($content);
var_dump($object);

good it is at least better organized.

a hug!

People are also looking for solutions to the problem: Translate XML to PHP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.