PHP Introduction | Using Text Files | Splitting and Processing Text (explode, implode)
Text files are used to process various kinds of data. For example, they are also used to create data laid out horizontally on the screen, like an Excel sheet.
If you know how to use this kind of text containing many data items, you can use text files as a simple database.
Let us try it in practice. First, change the contents of the sample data.txt text file as follows.
원석, won@flower.ko, 010-9999-9999
성진, sung@yamada.jp, 010-8888-8888
병호, byeong@baseball.com, 010-7777-7777
Here, personal information such as name, email address, and phone number is separated by commas and written line by line. This makes it possible to read each line of data and extract each item from it for processing.
Let us look at an example that reads and displays this data.
<?php
$lines = @file("data.txt") or $result = "Could not read the file.";
if ($lines != null) {
$result = '<table border="1">';
$result .= "<tr><th>NAME</th><th>MAIL</th><th>TEL</th></tr>";
for($i = 0; $i < count($lines); $i++){
$result .= "<tr>";
$arr = explode(",", $lines[$i]);
for($j = 0;$j < 3;$j++){
$result .= "<td>{$arr[$j]}</td>";
}
$result .= "</tr>";
}
$result .= "</table>";
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>sample page</title>
</head>
<body>
<h1>Hello PHP!</h1>
<p><?php echo $result; ?></p>
</body>
</html>
When accessed, the data appears in table form using an HTML table.
Here, the text is obtained from file as an array for each line, and a for loop processes it. Each retrieved line of text is split into three text values by commas and processed. In this example:
$arr = explode(",", $lines[$i]);
This is the part that separates the text in $lines[$i] by commas. explode is a function that splits the text in the second argument using the character specified in the first argument and returns it organized as an array. Here, a comma is specified as the first argument. As a result, the text in the second argument is separated by commas. The comma disappears from the split array text. In other words, when you split with explode, the separator character is removed, so be careful.
Conversely, you can also combine text organized in an array into a single text value using a specified separator.
$variable = implode(separator, array);
Using the implode function, the text of each element in an array is combined into one text value with the separator placed between elements. In other words, it can restore the array decomposed by explode. Remember them as a pair.