Ghi dữ liệu từ mảng vào File


Các bạn đã biết làm thế nào để ghi dữ liệu ra file và đọc dữ liệu từ file bằng PHP. Trong phần này, chúng tôi tiếp tục trình bày làm thế nào để đọc dữ liệu từ file vào biến mảng và in ra trang web.

Ví dụ 1: Đọc dữ liệu từ file vào mảng
<html>
<head>
  <title>Customer Orders</title>
</head>
<body>
<h2>Toyota's Auto Parts</h1>
<h3>Customer Orders</h2>
<?
   $fp = fopen("c:\inetpub\wwwroot\examples\files\order.txt", "r");
  $fp =$fp.'"\files\order.txt";
$fp =fopen($fp,"r");
   flock($fp, 1);   
//không tồn tại file  
   if (!$fp)
   {
     echo "<p><strong>No orders pending."
         ."Please try again later.</strong></p></body></html>";
     exit;
   }
// tìm thấy file trên orders.txt
   while (!feof($fp))
   {
      $order= fgets($fp, 100);
      echo $order."<br>";
   }
   flock($fp, 3);  
   fclose($fp);
?>
</body>
</html>
Trong ví dụ trên chúng tôi sử dụng hàm file để nạp tất cả dữ liệu trong file và mảng. Trong trường hợp bạn muốn đọc từng hàng dữ liệu trong file vào từng phần tử trong mảng, bạn có thể sử dụng hàm explode() để tách dữ liệu.
ví du: Đọc từng phần dữ liệu trong phần tử mảng:
<html>
<head>
  <title>Toyota's Auto Parts - Customer Orders</title>
</head>
<body>
<h3>Toyota's Auto Parts</h3>
<b>Customer Orders<b><br>
<?
//Đọc dữ liệu từ file vào biến cố order mỗi order là một phần tử của mảng
      $orders= file("c:\inetpub\wwwroot\examples\files\order.txt");
//Đếm số lượng order trong mảng order  
   $number_of_orders = count($orders);
   if ($number_of_orders == 0)
   {
     echo "<p><strong>No orders pending."
         ."Please try again later.</strong></p>";
   }
   echo "<table border=1>\n";
   echo "<tr><th bgcolor = \"#CCCCFF\">Order Date</td>
             <th bgcolor = \"#CCCCFF\">Tyres</td>
             <th bgcolor = \"#CCCCFF\">Oil</td>
             <th bgcolor = \"#CCCCFF\">Spark Plugs</td>
             <th bgcolor = \"#CCCCFF\">Total</td>
             <th bgcolor = \"#CCCCFF\">Address</td>
         <tr>";
   for ($i=0; $i<$number_of_orders; $i++)
   {
          $line = explode( "\t", $orders[$i] );
            $line[1] = intval( $line[1] );
      $line[2] = intval( $line[2] );
      $line[3] = intval( $line[3] );
      //Xuất dữ liệu cho mỗi order
      echo "<tr><td>$line[0]</td>
                <td align = right>$line[1]</td>
                <td align = right>$line[2]</td>
                <td align = right>$line[3]</td>
                <td align = right>$line[4]</td>
                <td>$line[5]</td>
            </tr>";
   }
   echo "</table>";
?>
</body>
</html>
Như trong ví dụ, hàm explode() với hai tham số, tham số thứ nhất là chuỗi "t" cho phép bạn truyền khoảng cách tab giữa hai phần tử, tham số thứ hai là một dòng dữ liệu ứng với biến $orders.


0 nhận xét to "Ghi dữ liệu từ mảng vào File"

Đăng nhận xét