skip to content

PHP: Formatting Data as HTML

 Tweet0 Shares0 Tweets

PHP: Formatting Data as HTML

A lot of PHP code is used to query a database, format the results and display them using HTML (or XHTML or XML or ...). Here are some quick solutions to common formatting problems.

Suppose you have the following data returned by a database query (an array of associative arrays with values for city and region):

cityregion
[0]BaltimoreMid-Atlantic
[1]ColumbusMidwest
[2]MilwaukeeMidwest
[3]IndianapolisMidwest
[4]DetroitMidwest
[5]ChicagoMidwest
[6]PhiladelphiaNortheast
[7]BostonNortheast
[8]New York CityNortheast
[9]Los AngelesPacific-West
[10]San FranciscoPacific-West
[11]San JoséPacific-West
[12]San DiegoPacific-West
[13]MemphisSouth
[14]DallasSouth-Central
[15]San AntonioSouth-Central
[16]AustinSouth-Central
[17]HoustonSouth-Central
[18]JacksonvilleSoutheast
[19]PhoenixSouthwest

Now clearly it's a trivial task to display this using a TABLE - as we've done above - you just make each record a row (TR), each value a cell (TD) and wrap the result in a table (TABLE).

But what if you want to improve the output, by allowing each 'region' to have a separate header and the related cities presented as a list underneath? There are many ways to do this, but the following is perhaps the most efficient.

Breaking into sections with headings

Firstly, we focus on the headings:

# initialise loop variable $lastregion = ''; # loop through query results foreach($result as $row) { extract($row); # region, city # check whether we need to display a new heading if($region != $lastregion) { # display heading echo "<h4>REGION: ",htmlspecialchars($region),"</h4>\n\n"; $lastregion = $region; } echo "<p>",htmlspecialchars($city),"</p>\n\n"; } # clean up variables unset($row, $region, $city, $lastregion)

Note: The data must first be sorted/grouped by region or the output will be a bit of a mess. The initial value of the lastregion variable can be any value that isn't present in that field/column of the data.

The output of the above code will be as follows:

REGION: Mid-Atlantic

Baltimore

REGION: Midwest

Columbus

Milwaukee

Indianapolis

Detroit

Chicago

REGION: Northeast

Philadelphia

Boston

New York City

REGION: Pacific-West

Los Angeles

San Francisco

San José

San Diego

REGION: South

Memphis

REGION: South-Central

Dallas

San Antonio

Austin

Houston

REGION: Southeast

Jacksonville

REGION: Southwest

Phoenix

So far so good. Now to format the list of cities under each region.

Headings with unordered lists

To do this, we're using unordered lists (UL) and require an extra variable to keep track of whether a list is currently open as we loop through the data:

# initialise loop variables $ulopen = false; $lastregion = ''; # loop through query results foreach($result as $row) { extract($row); # region, city # check if we need to display a new heading if($region != $lastregion) { # close list if there's one open if($ulopen) echo "</ul>\n\n"; # display heading echo "<h4>REGION: ",htmlspecialchars($region),"</h4>\n\n"; $lastregion = $region; # start new list echo "<ul>\n"; $ulopen = true; } echo " <li>",htmlspecialchars($city),"</li>\n"; } # don't forget to close the last list if($ulopen) echo "</ul>\n\n"; # clean up variables unset($row, $region, $city, $ulopen, $lastregion)

The output is now much cleaner - both in terms of the HTML semanatics and readability:

REGION: Mid-Atlantic

REGION: Midwest

REGION: Northeast

REGION: Pacific-West

REGION: South

REGION: South-Central

REGION: Southeast

REGION: Southwest

The examples above have been for a fairly simple dataset with few formatting requirement. In reality, you will be looking at more complex data and have different requirement with regards to formatting. The principle remains the same however, and the code presented above can be adapted to cater for most situations.

Here's one final example of presenting the same data as a hierarchical SELECT input in a FORM:

Select City: <select name="city"> <option value=""></option> <?PHP # initialise loop variables $optopen = false; $lastregion = ""; # loop through query results foreach($result as $row) { extract($row); # region, city # check if we need to start a new optgroup if($region != $lastregion) { # close optgroup if there's one open if($optopen) echo "</optgroup>\n\n"; # start new optgroup echo "<optgroup label=\"REGION: ",htmlspecialchars($region),"\">\n"; $lastregion = $region; $optopen = true; } echo " <option>",htmlspecialchars($city),"</option>\n"; } # don't forget to close the last optgroup if($optopen) echo "</optgroup>\n\n"; # clean up variables unset($row, $region, $city, $optopen, $lastregion) ?> </select>

Not all browsers will render this properly, but what you should end up with is a drop-down list with the regions as non-selectable headings and the cities grouped under them or as pop-out submenus:

Select City:

Working with a database

If you're querying a database then you may have trouble getting these examples to work as they assume the data is available in an associative array.

If instead you have a 'Database Resource' handle you can simply replace in each case:

foreach($result as $row) {

with:

while(false !== ($row = pg_fetch_assoc($result))) {

or for MySQL:

while(false !== ($row = mysql_fetch_assoc($result))) {

where $result is the database resource handle returned by pg_query or mysql_query.

< PHP

Send a message to The Art of Web:


used only for us to reply, and to display your gravatar.

CAPTCHA

<- copy the digits from the image into this box

press <Esc> or click outside this box to close

Post your comment or question
top