开发者

Reading and writing file to PHP, help with formatting?

开发者 https://www.devze.com 2023-02-19 14:17 出处:网络
I\'m writing this to a file: $myFile = \"purchases.txt\"; $fh = fopen($myFile, \'a\'); $stringData = $title .\"|\". $id;

I'm writing this to a file:

    $myFile = "purchases.txt";
    $fh = fopen($myFile, 'a');
    $stringData = $title ."|". $id;
        fwrite ($fh, $stringData."|");
    fclose ($fh);

In a separate file i'm writing the names:

  $name = $_POST['name'];
    $last = $_POST['lastname'];
    $name = $name ." ". $last;
    $myFile = "purchases.txt";
    $fh = fopen($myFile, 'a');
    $stringData = $name;
    fwrite ($fh, $stringData."\r\n");
    fclose ($fh);

And echo-ing the contents:

foreach($lines as $theline ) {
            list($title, 开发者_StackOverflow$id, $name) = split('\|',$theline); 
                    echo "
                        <tr><td><h3>Title</h3></td>
                        <td><h3>ID</h3></td>
                        <td><h3>Name</h3></td>
                        <td><h3>Date</h3></td>
                         <tr><td><h4>$title</h4></td>
                         <td><h4>$id</h4></td>
                         <td><h4>$name</h4></td>
                         <td><h4>".date('l \\t\h\e jS')."</h4></td></tr>
                         ";                  
                     }

File looks like this:

 Uncharted 3 |1| Deus Ex |2| Metal Gear Solid |3|Lib drfsdgf

Problem: If there's more than one game title in the file, it prints the title in place of the customer name to the table.


Consider storing your data in json or xml format. Then, when you read it out, you can use built-in php functions to read it correctly.

json_encode and json_decode are your friends.

Edit: Above advice still applies, but I just noticed the 2 different files aspect.

This solution won't work as well, since you're adding to the data twice. Either clean up the way you add the data to your file (fully build the string, then write it to your file), or switch to a database. Databases are designed to handle problems like this much more gracefully.

0

精彩评论

暂无评论...
验证码 换一张
取 消