Czech version
logolink

< Back to the list of lessons

Visualizing Text File inside the WWW Page

PHPContent of the lesson:

  • Problems with Processing Data to Rows
  • Solution 2 - Dividing Columns to Variables
  • Function Explode
  • Example of Table with Three Columns
  • Individual Task - Construct List
  • Homework

Problems with Processing Data to Rows

This lesson requires the result of this lesson: Processing and Editing Text File in PHP.

Try to consider possible problems of our solution to visualize the text file from the previous lesson. When we will not be able to use the simple replacement?

  • What if we wanted to output only some columns?
  • What if we wanted to change the order of columns?
  • What if we wanted to adjust several columns (for example phone number, e-mail)?
  • What if we wanted to merge several columns?
  • What if we wanted to display a photo instead of the name?

All these questions lead us to the fact that we need the ability to manipulate with every column separately. We want to be able to access each column separately and adjust it as we want.

Solution 2 - Dividing Columns to Variables

An ideal situation would be if we were able to do something like this: "Save the content of the cell jmeno inside the variable $jmeno, content of the cell prijmeni inside the variable $prijmeni ... and then write only some of these variables into the HTML code.". To get a solution like this you have to use one of the PHP functions - the function explode.

Function Explode

To divide a string of variables connected by a separator (usually semicolon) to single parts you can use the function explode (description). This function requires two parameters at least:

  • source string - represents the string which we want to be divided to parts (the variable $radek in our case).
  • separator - this parameter contains the separator - this is a string which is used to separate the parts of the source string.

This function returns an array of all variables (the length can differ according to the source string). You can see that arrays in PHP are indexed from 0.

Using the function explode
$pole = explode(";",$radek);
vizualizace principu funkce explode

After this command we can use every part separately. We can write any combination of columns as we want. Take a look at the following sample.

Example of Table with Three Columns

We might want to write a simple table with three columns which should look like the following one (only first two rows are available):

Last Name, First Name, Title Abbreviation Phone number
Babíková Eliška   577007450
Bárta Radim, Mgr. Bár 577007448

You can see several problems in these two rows:

  • Not all employees have a title so you should add additional conditions.
  • Not all employees have an abbreviation assigned (they do not need it because they do not figure in the schedule).

Before editing our script we should think about the variables we are interested in for our output:

  • First Name - create a new variable $jmeno and assing the item from $pole on the position 0 into it. Add this command: $jmeno = $pole[0];
  • Last Name - create a new variable $prijmeni and assing the item from $pole on the position 1 into it. Add this command: $jmeno = $pole[1];
  • Title - create a new variable $titul and assing the item from $pole on the position 2 into it. Add this command: $jmeno = $pole[2];
  • Phone number - create a new variable $telefon and assing the item from $pole on the position 4 into it. Add this command: $jmeno = $pole[4];
  • Abbreviation - create a new variable $zkratka and assing the item from $pole on the position 6 into it. Add this command: $jmeno = $pole[6];

We did not have to create these variables but we did create them to better orientate inside our program. It is even better not to create additional variables. Why? Because you create copies of existing variables and need more memory to run your script which is not a good idea. However, we will use these variables in the next steps so leave them created.

We will modify our script:

Script
<?php
error_reporting(E_ALL ^ E_NOTICE);
$nazev_souboru="data/zamestnanci.csv";
if (file_exists($nazev_souboru)) {
	$soubor=fopen($nazev_souboru, "r");
	if($soubor){
		$pocetradku = 0;
		while (!feof($soubor)){
			$pocetradku = $pocetradku + 1;
			$radek = fgets($soubor,5000);
			if ($pocetradku == 1) {
				print("<h1>".$radek."</h1>");
			} else {
				if ($pocetradku == 2){
					print("<table cellspacing=\"0\" cellpadding=\"0\">");
					print("<thead><tr><th>Last Name, First Name, Title</th><th>Abbreviation</th><th>Phone</th></tr></thead>");
					print("<tbody>");
				}else{
					$pole = explode(";",$radek); 
					$jmeno = $pole[0];
					$prijmeni = $pole[1];
					$titul = $pole[2];
					$telefon = $pole[4];
					$zkratka = $pole[6];
					print("<tr>");
					print("<td>".$prijmeni." ".$jmeno);
					if ($titul<>""){
						print(", ".$titul); 
					}
					print("</td><td>".$zkratka."</td><td>".$telefon."</td>");
					print("</tr>");
				}
			}
		}
		print("</tbody>");
		print("</table>");
	} else {
		print("Soubor ".$nazev_souboru." se nepodařilo otevřít pro čtení."); 
	}
} else {
	print("Soubor ".$nazev_souboru." neexistuje.");
}
?>
              

We did two more adjustments of the nested condition if ($pocetradku == 2). The first one is that we wrote the titles of columns from our table by hand and did not use their titles from the CSV file. We have full control over the titles now.

Part of script which generates the header of the table
if ($pocetradku == 2){
    print("<table cellspacing=\"0\" cellpadding=\"0\">");
    print("<thead><tr><th>Last Name, First Name, Title</th><th>Abbreviation</th><th>Phone</th></tr></thead>");
    print("<tbody>");
}else{
          

The second adjustment is using the explode function to divide the line to single values. We created variables for single columns from the array and saved corresponding values inside. The process can be described in these steps:

  1. Insert the tag for the beginning of row (print("<tr>");).
  2. The next step is adding the beginning tag for a cell which will contain the Last Name and the First Name.
  3. Before ending the cell our script evaluates whether an employee has a title - if true then the title is written.
  4. The first cell is closed and two more cells with the abbreviation and the phone number are added.
  5. The HTML tag to end the row is inserted.
Part of script which writes single lines of table
}else{
    $pole = explode(";",$radek); 
    $jmeno = $pole[0];
    $prijmeni = $pole[1];
    $titul = $pole[2];
    $telefon = $pole[4];
    $zkratka = $pole[6];
    print("<tr>");
    print("<td>".$prijmeni." ".$jmeno);
    if ($titul<>""){
        print(", ".$titul); 
    }
    print("</td><td>".$zkratka."</td><td>".$telefon."</td>");
    print("</tr>");
}
          

Individual Task - Construct List

Try to find information about the function list in PHP (use the Internet). Try to understand its functionality and consider using it inside our program. How can it be used?

The List Function

This function can assign items of array into a list of variables (description). This function has n parameters - variables. To this "function" (it is a constructor rather than a function) of n arguments (n variables) is assigned an array. The first item of the array will be assigned inside the first argument (variable), the second item inside the second variable...

We can show the functionality of the constructor list using an easy example. Consider an array $logininfo=(333,michalmiklas,XDfg4rF,Michal,Miklas). Execute the command list($uid,$login,$encryptedpasswd,$name, $surname) = $logininfo;. What will happen? A variable $uid will be created and assigned with value 333, variable $login will be created and assigned with value michalmiklas ... and finally the variable $surname will store the value Miklas.

Usage of the function list
$list($promenna-0, promenna-1, ... , $promenna-n) = $pole; /* $pole should contain n+1 items */

Solution of the Construct List

We will use the construct list in our script instead of using single commands like $jmeno = $pole[0];, $prijmeni = $pole[1];,... to put the values of $pole inside variables.

Part of the script before using the construct list
}else{
    $pole = explode(";",$radek); 
    $jmeno = $pole[0];
    $prijmeni = $pole[1];
    $titul = $pole[2];
    $telefon = $pole[4];
    $zkratka = $pole[6];
    print("<tr>");
    print("<td>".$prijmeni." ".$jmeno);
    if ($titul<>""){
        print(", ".$titul); 
    }
    print("</td><td>".$zkratka."</td><td>".$telefon."</td>");
    print("</tr>");
}
          
Part of the script with the construct list
}else{
	list($jmeno,$prijmeni,$titul,$email,$telefon,$fotografie,$zkratka) = explode(";", $radek);
    print("<tr>");
    print("<td>".$prijmeni." ".$jmeno);
    if ($titul<>""){
        print(", ".$titul); 
    }
    print("</td><td>".$zkratka."</td><td>".$telefon."</td>");
    print("</tr>");
}
          

The final file can be downloaded here: zpracovani-souboru-3.rar. You can also see the previous solution without construct list in this file (it is closed into comment marks).

Homework

Try to adjust the script to write only employees with filled phone number.

Try to write the number of employees after the headline and before the table. That means you should add a sentence "Total number of employees: " and the number of employees who are inside the following table.

Additional Texts

Links

Questions

  1. Explain the functionality of the final script in this lesson.
  2. Explain the function explode and show its usage on an example.
  3. Explain the construct list and show its usage on an example.
webdesign, xhtml, css, php - Mgr. Michal Mikláš