[ Team LiB ] Previous Section Next Section

24.3 Setting Document Type

By default, PHP sends an HTTP header specifying the document as being HTML. The Content-Type header specifies the MIME type text/html, and the browser interprets the code as HTML. Sometimes you will wish to create other types of documents with PHP. Chapter 25 discusses creating images, which may require an image/png content type. MIME types are administered by IANA, the Internet Assigned Numbers Authority. You can find a list of official media types at <http://www.isi.edu/in-notes/iana/assignments/media-types/>.

At times, you may wish to take advantage of how browsers react to different types of content. For example, text/plain displays in a fixed-width font with no interpretation of HTML. If you use */* for the content type, the browser displays a dialog window for saving the file. Perhaps the most interesting use is for launching a helper application.

Listing 24.5 creates a tab-delimited text file that may launch Microsoft Excel. Take note that the computer must meet a few qualifications, however. First, it probably needs to be running Windows, and it must have Microsoft Excel installed. Newer versions of Excel associate the application/vnd.ms-excel content type with .xls files. My experience has been that these headers will cause an Excel OLE container inside either MSIE or Netscape Navigator on a Windows machine, but your experience may differ. Other browsers will likely ask the user if the file should be saved.

Notice the second header in Listing 24.5, Content-Disposition. This is not part of the HTTP 1.1 standard, but most browsers recognize it. It allows you to suggest a filename. If you add attachment; to the header, the browser may choose to open Excel in a separate window.

Listing 24.5 Sending a tab-delimited Excel file
<?php
    //set the document type
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: filename=\"listing24-5.txt\"");

    //send some tab-delimited data
    print("Listing 24-5\r\n");

    for($i=1; $i < 100; $i++)
    {
        print("$i\t");
        print(($i * $i) . "\t");
        print(($i * $i * $i) . "\r\n");
    }
?>

Using Content-Type this way is almost black magic, since browsers don't follow a standard when encountering different MIME types. This technique has proven to be most successful for me when writing intranet applications where I had the luxury of serving a narrow set of browsers.

    [ Team LiB ] Previous Section Next Section