Tag Archive ดาต้า

curl: ส่งไฟล์

และแล้วก็มาถึงจุดที่รอคอย การส่งไฟล์ด้วย curl เหมือนที่ user upload ไฟล์เข้าเว็บ เหมาะกับการเอาไปเขียนโปรแกรมทรานสเฟอร์ไฟล์จากเว็บหนึ่งไปอีกที่หนึ่ง หรือจะเขียน bot ส่งไฟล์ออกไปเก็บเป็นข้อมูลสำรองก็ได้

[code language=”php” title=”curl_file.php”]<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>CURL: send file</title>
<link href="../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>

<body>
<div class="container">
<?php
if (count($_FILES) || count($_POST)) {
$url = ‘http://localhost/snippets/PHP/variables.php’;

if (count($_FILES)) {
$file_name_with_full_path = $_FILES[‘avatar’][‘tmp_name’];

if (function_exists(‘curl_file_create’)) {
/* php 5.5+ */
$_POST[‘avatar’] = curl_file_create($file_name_with_full_path);
} else {
$_POST[‘avatar’] = ‘@’ . realpath($file_name_with_full_path);
}
}

$ch = curl_init();

curl_setopt_array($ch, [
CURLOPT_ENCODING => ‘UTF-8’,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $_POST,
//CURLOPT_POSTFIELDS => http_build_query($_POST),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $url,
]);

$result = curl_exec($ch);
curl_close($ch);

echo $result;
}
?>
<form action="curl_file.php" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input class="form-control" id="name" name="name" type="text">
</div>
<div class="form-group">
<label for="avatar">Avatar:</label>
<input accept="image/gif, image/jpeg, image/x-png" class="form-control" id="avatar" name="avatar" type="file">
</div>
<div class="form-group">
<label for="address1">text address:</label>
<input class="form-control" id="address1" name="address[d]" type="text">
</div>
<div class="form-group">
<label for="address2">text address 2:</label>
<input class="form-control" id="address2" name="address[f]" type="text">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</body>

</html>[/code]

แต่เพราะ bug ของ function http_build_query ไม่สามารถ encoded query string ในกรณีที่มีไฟล์ได้อย่างถูกต้อง ทำให้ต้องส่งค่าฟอร์มไปโดยไม่เข้ารหัส ดังนั้น ค่าที่เป็น array จึงส่งค่าออกไปผิด[code language=”php” title=”function http_build_query bug”][address]Array
(
[name] => pitt phunsanit
[address] => Array
)[/code]

จากที่ค้นหาข้อมูลดู ยังไม่มีวิธีที่แก้ปัญหานี้ได้โดยไม่มีผลอาการข้างเคียง คงต้องรอให้ทางทีมงานพัฒนา PHP แก้ปัญหาให้ ตอนนี้ก็พยามหลีกเลี่ยงการส่งข้อมูลแบบเป็นอาร์เรไปก่อน อาจจะใช้ implode รวมข้อมูลก่อนส่งไปก็ได้

curl: ส่ง ฟอร์มแบบ post

หลังจากตัวอย่าง curl: ส่ง ฟอร์มแบบ get เรามาลองส่งข้อมูลแบบโพสต์กันต่อ เว็บไซต์ส่วนใหญ่จะนิยมส่งค่าในแบบฟอร์มแบบ post มากกว่าแบบ get เพราะว่า url จะดูสวยงาม ไม่เละเทะ ดูแล้วสบายตา และปลอดภัยกว่าการส่ข้อมูลให้เห็นง่ายๆ แบบใช้ url

[code language=”php” title=”curl_post.php”]<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>CURL: send post variables</title>
<link href="../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>

<body>
<div class="container">
<?php
if (count($_POST)) {
$url = ‘http://localhost/snippets/PHP/variables.php’;

$ch = curl_init();

curl_setopt_array($ch, [
CURLOPT_ENCODING => ‘UTF-8’,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query($_POST),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $url,
]);

$result = curl_exec($ch);
curl_close($ch);

echo $result;
}
?>
<form action="curl_post.php" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input class="form-control" id="name" name="name" type="text">
</div>
<div class="form-group">
<label for="avatar">Avatar:</label>
<input accept="image/gif, image/jpeg, image/x-png" class="form-control" id="avatar" name="avatar" type="file">
</div>
<div class="form-group">
<label for="address1">text address:</label>
<input class="form-control" id="address1" name="address[]" type="text">
</div>
<div class="form-group">
<label for="address2">text address 2:</label>
<input class="form-control" id="address2" name="address[]" type="text">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</body>

</html>[/code]

จากการเปลี่ยน option ของ curl เล็กน้อยการส่งข้อมูลก็เปลี่ยนไปเป็นแบบ method post แล้ว แต่ก็ยังส่งไฟล์ไปไม่ได้อยู่ดีๆ ใจเย็นๆ ครับบทความหน้าส่งไฟล์ออกไปแน่ๆ ครับ

curl: ส่ง ฟอร์มแบบ get

curl หรือ Client URL Library เป็น function ที่ทำให้ php ทำตัวเป็น browser ที่ใช้เปิดเว็บรับส่งข้อมูลต่างๆ จาก server ของเราไปเซิฟเวอร์เครื่องอื่นๆ

ตัวอย่างการใช้งานที่ง่ายที่สุด คือการใช้ curl โดยการจำลองการส่งข้อมูลจากฟอร์มแบบเมธอดเก็ต หรือที่เรียกง่ายๆว่า ส่งข้อมูลแบบ url นั่นละ

[code language=”php” title=”curl_get.php”]<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>CURL: send get variables</title>
<link href="../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>

<body>
<div class="container">
<?php
if (count($_GET)) {
$queryString = http_build_query($_GET);
$url = ‘http://localhost/snippets/PHP/variables.php?’ . $queryString;

echo ‘<br>$url = ‘, $url;

$ch = curl_init();

curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $url,
]);

$result = curl_exec($ch);
curl_close($ch);

echo $result;
}
?>
<form action="curl_get.php" method="get">
<div class="form-group">
<label for="name">Name:</label>
<input class="form-control" id="name" name="name" type="text">
</div>
<div class="form-group">
<label for="avatar">Avatar:</label>
<input accept="image/gif, image/jpeg, image/x-png" class="form-control" id="avatar" name="avatar" type="file">
</div>
<div class="form-group">
<label for="address1">text address:</label>
<input class="form-control" id="address1" name="address[]" type="text">
</div>
<div class="form-group">
<label for="address2">text address 2:</label>
<input class="form-control" id="address2" name="address[]" type="text">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</body>

</html>[/code]ในการแปลงข้อมูลจากแบบฟอร์มจะใช้ [code language=”php” title=”Generate URL-encoded query string”]$queryString = http_build_query($_GET);[/code] แปลงให้อยู่ในรูปแบบคิวรี่สตริงที่ส่งไปกับ url ได้

การทดสอบทำได้โดยไฟล์ variables.php จำลองเป็นฝั่งรับข้อมูล[code language=”php” title=”variables.php”]<?php
echo ‘<h3>$_COOKIE</h3><pre>’, print_r($_COOKIE, true), ‘</pre>’;
echo ‘<h3>$_FILES</h3><pre>’, print_r($_FILES, true), ‘</pre>’;
echo ‘<h3>$_GET</h3><pre>’, print_r($_GET, true), ‘</pre>’;
echo ‘<h3>$_POST</h3><pre>’, print_r($_POST, true), ‘</pre>’;
echo ‘<h3>$_REQUEST</h3><pre>’, print_r($_REQUEST, true), ‘</pre>’;
[/code]

ข้อมูลที่ส่งไปจะแสดงกลับมาให้เราเห็น แต่สังเกตุได้ว่า ถึงจะส่งไฟล์ avatar ฝั่งรับก็จะไม่ได้รับ เพราะการส่งข้อมูลแบบนี้จะมีข้อเสียคือ ไม่สามารถส่งไฟล์ได้

PHPExcel: จัดรูปแบบ format ข้อมูล

เมื่อวานเขียน export ข้อมูลออกเป็นไฟล์ excel โดยใช้เวลาไม่นาน เพราะโครงสร้างการทำงานมันเหมือนๆ งานที่เคยทำมา แต่มาตกม้าตายเอาที่การฟอร์เมตของแต่ละ column ให้ตรงกับชนิดข้อมูล เช่น type เป็น date ก็ควรให้เห็นเป็นวันที่ไม่ใช่เลข 1234155 อะไรก็ไม่ทราบ

[code language=”php” title=”PHPExcel/columnsType.php”]<?php

include ‘../vendor/phpoffice/phpexcel/Classes/PHPExcel.php’;

set_time_limit(0);

$objPHPExcel = new PHPExcel();

/* Set default style */
$defaultStyle = $objPHPExcel->getDefaultStyle();

$defaultStyle->getFont()
->setName(‘Arial’)
->setSize(11);

$defaultStyle->getNumberFormat()
->setFormatCode(‘yyyy-mm-dd’);

/* Set document properties */
$title = ‘columnsType_’ . date(‘Y-m-d_H:i’);
$objPHPExcel->getProperties()->setCreator(‘CMS’)
->setCategory(‘Exports Datas’)
->setDescription($title)
->setKeywords(‘Exports Datas ‘ . date(‘Y-m-d’))
->setSubject($title)
->setTitle($title);

/* create new sheet */
$objWorkSheet = $objPHPExcel->getActiveSheet();
$objWorkSheet->setTitle(‘Exports Datas’);

$columns = [
‘row_number’ => [‘title’ => ‘No.’, ‘type’ => ‘row_number’],

‘price’ => [‘title’ => ‘ราคา’, ‘type’ => ‘currency’],

‘dateEnd’ => [‘title’ => ‘เริ่มจำหน่าย’, ‘type’ => ‘date’],
‘dateStart’ => [‘title’ => ‘เริ่มจำหน่าย’, ‘type’ => ‘date’],

‘dateApproved’ => [‘title’ => ‘เวลาอนุมัติ’, ‘type’ => ‘datetime’],

‘height’ => [‘title’ => ‘สูง (เมตร)’, ‘type’ => ‘float’],
‘width’ => [‘title’ => ‘กว้าง (เมตร)’, ‘type’ => ‘float’],

‘calculate’ => [‘title’ => ‘สูตรคํานวณหวย’, ‘type’ => ‘formula’],

‘image’ => [‘title’ => ‘ภาพ’, ‘type’ => ‘image’],

‘items’ => [‘title’ => ‘จำนวน’, ‘type’ => ‘integer’],

‘productName’ => [‘title’ => ‘ชื่อสินค้า’, ‘type’ => ‘string’],

‘timeEnd’ => [‘title’ => ‘เวลาขาย’, ‘type’ => ‘time’],
‘timeStart’ => [‘title’ => ‘เวลาปิดการขาย’, ‘type’ => ‘time’],

‘url’ => [‘title’ => ‘page’, ‘type’ => ‘url’],
];

/* header */
$colNo = -1;
$rowNo = 1;
$colStrings = [];
foreach ($columns as $fieldId => $field) {
$colNo++;
$colStrings[$colNo] = $colString = PHPExcel_Cell::stringFromColumnIndex($colNo);
$objWorkSheet->setCellValue($colString . ‘1’, $field[‘title’]);
$objWorkSheet->setCellValue($colString . ‘2’, ‘type = ‘ . $field[‘type’]);
}
$headerHeight = $rowNo = 2;

$objPHPExcel->getActiveSheet()->freezePane($colString . ($headerHeight + 1));

/* random data */
$datas = [];
for ($a = 0; $a < 10; $a++) {
$temp = [];

$temp[‘calculate’] = ‘=RAND()’;
$temp[‘dateApproved’] = date(DATE_ISO8601, mt_rand(0, 1499291999));
$temp[‘dateEnd’] = date(‘Y-m-d’, mt_rand(0, 1499291999));
$temp[‘dateStart’] = date(‘Y-m-d’, mt_rand(0, 1499291999));
$temp[‘height’] = mt_rand(0, 10) / 10;
$temp[‘image’] = ‘http://lorempixel.com/400/200/sports/?st=’ . mt_rand(1, 500);
$temp[‘items’] = mt_rand(999, 9999999);
$temp[‘price’] = mt_rand(100, 10000);
$temp[‘productName’] = substr(str_shuffle(str_repeat($x = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’, ceil(10 / strlen($x)))), 1, 10);
$temp[‘timeEnd’] = date(‘H:i:s’, mt_rand(0, 1499291999));
$temp[‘timeStart’] = date(‘H:i:s’, mt_rand(0, 1499291999));
$temp[‘url’] = ‘https://plusmagi.com/?s=’ . mt_rand(1, 500);
$temp[‘width’] = mt_rand(0, 10) / 10;

array_push($datas, $temp);
}

/* add data */
$row_number = 0;
foreach ($datas as $item) {
$colNo = -1;
$row_number++;
$rowNo++;
foreach ($columns as $fieldId => $field) {
$colNo++;

$coordinate = $colStrings[$colNo] . $rowNo;

switch ($field[‘type’]) {
case ‘date’:
case ‘datetime’:
case ‘time’:{
$ts = strtotime($item[$fieldId]);
$value = PHPExcel_Shared_Date::PHPToExcel($ts);
}break;

case ‘image’:{
$value = $item[$fieldId];

$gdImage = imagecreatefromjpeg($value);
$objDrawing = new PHPExcel_Worksheet_MemoryDrawing(); /*create object for Worksheet drawing*/

$objDrawing->setCoordinates($coordinate); /*set image to cell*/
$objDrawing->setDescription(‘Customer Signature’); /*set description to image*/
$objDrawing->setHeight(50);
$objDrawing->setImageResource($gdImage);
$objDrawing->setName(‘Customer Signature’); /*set name to image*/
$objDrawing->setOffsetX(25); /*setOffsetX works properly*/
$objDrawing->setOffsetY(10); /*setOffsetY works properly*/
$objDrawing->setWidth(100); /*set width, height*/

$objDrawing->setWorksheet($objWorkSheet); /*save*/

$objWorkSheet->getRowDimension($rowNo)->setRowHeight(60); /* set row height*/
}break;

case ‘row_number’:{
$value = $row_number;
}break;

case ‘url’:{
$value = str_replace(‘http://’, ”, $item[$fieldId]);
$objWorkSheet->getCell($coordinate)
->getHyperlink()
->setTooltip(‘Click here to access page’)
->setUrl($item[$fieldId]);
}break;

default:{
$value = $item[$fieldId];
}break;
}

$objWorkSheet->setCellValue($coordinate, $value);
}
}

/* auto width column */
$cellIterator = $objWorkSheet->getRowIterator()->current()->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
$objWorkSheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
}

/* format for columns */
$colNo = -1;
foreach ($columns as $fieldId => $field) {
$colNo++;

$coordinate = $colStrings[$colNo] . ($headerHeight + 1) . ‘:’ . $colStrings[$colNo] . $rowNo;

switch ($field[‘type’]) {

case ‘currency’:{
$objWorkSheet->getStyle($coordinate)
->getNumberFormat()
->setFormatCode(‘#,##0.00’);
/*->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);*/
}break;

case ‘date’:{
$objWorkSheet->getStyle($coordinate)
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH);
}break;

case ‘datetime’:{
$objWorkSheet->getStyle($coordinate)
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME);
/*->setFormatCode(‘Y-m-d H:i:s’);*/
}break;

case ‘float’:{
$objWorkSheet->getStyle($coordinate)
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
}break;

case ‘integer’:
case ‘row_number’:{
$objWorkSheet->getStyle($coordinate)
->getNumberFormat()
->setFormatCode(‘#,##’);
}break;

case ‘time’:{
$objWorkSheet->getStyle($coordinate)
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4);
/*->setFormatCode(‘Y-m-d H:i:s’);*/
}break;

default:{
$objWorkSheet->getStyle($coordinate)
->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_GENERAL);
}break;
}

}

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel2007’);
header(‘Content-Type: application/vnd.ms-excel’);
header(‘Content-Disposition: attachment;filename="’ . $title . ‘.xlsx"’);
header(‘Cache-Control: max-age=0’);
header(‘Cache-Control: no-store, no-cache, must-revalidate, max-age=0’);
header(‘Cache-Control: post-check=0, pre-check=0’, false);
header(‘Pragma: no-cache’);
$objWriter->save(‘php://output’);[/code]

หลักการต้องทำงานคู่กัน 2 ส่วนคือ

  1. ส่วนใส่ข้อมูล บางชนิดต้องแปลงข้อมูลก่อน เช่น date, datetime, timestamp และ time ต้องเปลี่ยนเป็น unix timestamp ก่อน
  2. ส่วนกำหนด cell format (ในตัวอย่างให้วิธีกำหนดทั้ง column ไปเลย) ต้องเลือกรูปแบบที่เหมาะสมโดยจะกำหนดเอง[code language=”php” title=”custom format”]->setFormatCode(‘Y-m-d H:i:s’);[/code] หรือจะใช้ตามมาตราฐานก้ได้ Class PHPExcel_Style_NumberFormat ก็ได้

สร้างไฟล์ csv จาก phpexcel

phpexcel สร้างไฟล์ excel ได้สะดวกมาก แต่ไม่ใช่ทุกระบบจะสามารถ import ข้อมูลจากไฟล์แบบเอ็กเซลได้ การส่งออกไฟล์แบบตัวอักษรล้วนๆ และใช้เครื่องหมายคั่นแบบไฟล์ csv จึงยังจำเป็นอยู่

ที่สำคัญคือสามารถแก้หรือเพิ่มเงื่อนไขจาก code ส่งออกข้อมูลเป็น excel โดย phpexcel ที่มีอยู่เดิม โดยดัดแปลงเล็กน้อยในส่วน header และการ write data[code language=”php” title=”PHPExcel_writer_csv.php”]<?php

/* PHPExcel_IOFactory – Reader */
include ‘PHPOffice/PHPExcel/Classes/PHPExcel.php’;

$objPHPExcel = new PHPExcel();

/* Set default style */
$defaultStyle = $objPHPExcel->getDefaultStyle();

$defaultStyle->getFont()
->setName(‘Arial’)
->setSize(11);

$defaultStyle->getNumberFormat()
->setFormatCode(‘yyyy-mm-dd’);

/* Set document properties */
$title = ‘Exports_Datas_’ . date(‘Y-m-d_H:i’);
$objPHPExcel->getProperties()->setCreator(‘Pitt Phunsanit’)
->setCategory(‘Exports Datas’)
->setDescription($title)
->setKeywords(‘Exports Datas ‘ . date(‘Y-m-d’))
->setSubject($title)
->setTitle($title);

/* rename sheet */
$objWorkSheet = $objPHPExcel->getActiveSheet();
$objWorkSheet->setTitle(‘Exports Datas’);

for ($rowNo = 1; $rowNo < 10; $rowNo++) {
for ($colNo = 0; $colNo < 5; $colNo++) {

$insert = rand(0, 1);
if($insert == 1) {

$colString = PHPExcel_Cell::stringFromColumnIndex($colNo);

$coordinate = $colString . $rowNo;

$objWorkSheet->setCellValue($coordinate, ‘ส่งออกข้อมูล -> ‘.$coordinate);
}
}
}

header(‘Cache-Control: max-age=0’);
header(‘Content-Encoding: UTF-8’);
header(‘Content-Description: File Transfer’);
header(‘Content-Type: application/octet-stream’);
header(‘Content-type: text/csv; charset=UTF-8’);
header(‘Content-Disposition: attachment;filename="’.$title.’.csv"’);
echo "\xEF\xBB\xBF"; /* UTF-8 BOM */

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘CSV’);

/* set Delimiter, (defaults ,) */
//$objWriter->setDelimiter(‘|’);
//$objWriter->setEnclosure(”);
/* Set line ending (defaults PHP_EOL) */
//$objWriter->setLineEnding(‘0x0d0a’);

$objWriter->save(‘php://output’);[/code]

ถ้าสังเกตุจะมี $insert = rand(0, 1); และ if($insert == 1) { ทำให้บาง cell ไม่มีข้อมูล เพื่อที่จะแสดงให้เห็นว่าการใช้ phpexcel จะดีกว่าการใช้ echo ส่งออกข้อมูลแบบที่ง่ายที่สุด (CSV) ในกรณีที่บางคอลัมข้อมูลไม่มี เราไม่จำเป็นต้อง echo ค่าว่าง หรือมานับ , ว่าครบมั๋ย phpexcel จะจัดการให้เอง

ถ้าเปลี่ยนรูปแบบอื่นเช่น

  • ต้องการใช้เครื่องหมายอื่นเช่น pipe | ก็สามารถกำหนดโดยใช่ setDelimiter
  • ต้องการ wrap ข้อมูลก็ใช้ setEnclosure จะปิดหัว ปิดท้ายข้อมูลแต่ละ cell ให้
  • ต้องการใช้เครื่องมายอื่นในการแบ่งข้อมูลออกเป็นชุดๆ ก็ setLineEnding

เขียนครั้งเดียวส่งออกข้อมูลได้ 2 รูปแบบ ส่วนคำสั่งที่ไม่ได้ใช้ในรูปแบบ csv เช่น setTitle ก็ไม่ทำให้มี error ดีจริงๆ phpexcel

ส่งออกข้อมูลแบบที่ง่ายที่สุด (CSV)

วิธีที่ส่งออกข้อมูลที่ง่ายที่สุด และอิมพอร์ตเข้าโปรแกรมต่างๆได้มากที่สุดคือ comma-separated values (CSV) แปลง่ายๆว่า ไฟล์ตารางที่คั่นด้วยคอมม่า แปลบ้านๆไปอีกคือ text file ที่ข้อมูลถูกแบ่งโดย , หรือเครื่องหมายอื่นเช่น pipe | โดยข้อมูลต่ละ record จะแบ่งโดยการขึ้นบรรทัดใหม่ (ใน php คือ \n)

เขียนง่ายๆ แค่มีการเพิ่ม header เข้าไปว่ามันเป็น csv นะและ echo ธรรมดาๆ[code language=”php”]<?php

$filename = ‘Exports_Datas_’ . date(‘Y-m-d_H:i’);

header(‘Cache-Control: max-age=0’);
header(‘Content-Encoding: UTF-8’);
header(‘Content-Description: File Transfer’);
header(‘Content-Type: application/octet-stream’);
header(‘Content-type: text/csv; charset=UTF-8’);
header(‘Content-Disposition: attachment;filename="’.$filename.’.csv"’);
echo "\xEF\xBB\xBF"; /* UTF-8 BOM */

/* random add datas */
for($a = 0; $a < 10; $a++) {
$datas = [];
for($b = 0; $b < 5; $b++) {
$datas[$b] = ‘ส่งออกข้อมูล ‘.rand(1, 100);
}
echo implode(‘,’, $datas)."\n";
}[/code]

หลังจากเรียกไฟล์ php ก็จะเห็นว่ามีการให้ download ขึ้นมาให้ save ลองคลิกเปิดดูถ้าเครื่องมี excel อยู่ก็จะเปิดอ่านข้อมูลได้ทันที หรือจะใช้ text editor เปิดขึ้นมาดูก็ได้ ทดลองเปลี่ยนเป็นให้ดึงข้อมูลจาก database ดูครับ