PHP Header: XML Header Coding Tutorial

php header xmlXML stands for Extensible Markup Language. This language defines rules for encoding documents such that they are both human and machine readable. The objective is to be simple, general and usable over the Internet. It’s often used for the representation of arbitrary data structures such as in web services. The major use of XML is for interchange of data over the Internet. PHP is an open source programming language mainly used for dynamic web content and server-side applications. It is characterized by flexibility of use as well ease of learning. The syntax is particularly simple and many PHP programmers know no other language. It is growing in popularity and has been used to create several robust and efficient sites.  In this intermediate level tutorial we look at how you can create an XML header with PHP that allows your document to be read as an XML document. You require a basic level of familiarity with PHP. If you’re new, you may want to first take this beginners course to learn the ropes with PHP.

Certain programming languages have a divided file structure consisting of a header file and an implementation file. While the header file defines the interface of the functions and subroutines with the rest of the code, the implementation defines the function of the code. However, PHP lacks this divided file architecture. It has a mechanism to include a PHP file within another. Using the included statement you can write a PHP file of core functions and be able to include those functions required by another PHP file. You can learn more about this in our PHP 101 course.

Benefits  of PHP

PHP offers support for different types of databases which make it ideal for applications that need to interact with databases. One of the significant advantages of using PHP is that it is open source. The developers of PHP have created an exhaustive online resource covering all language functions along with examples of how to use them. This is responsible for making PHP easier to learn compared to other languages. It also boasts of  having a number of online support groups. As it is a flexible programming language, it supports object oriented programming but can also function independently without OOPs.

PHP and XML

PHP supports text processing which includes many extensions to parse and access XML documents. It standardizes all of the XML extensions on the solid base of libxml2 and adds support for SimpleXML, XMLReader and XMLWriter. Note that the XML functions are the part of the PHP code and do not require installation in order to be used. The XML functions in PHP cannot validate XML documents.  You may want to learn more about XML programming with this course, to see how it fits in with PHP.

What is a Header?

Each document read by a web browser requires a header. This is because the header tells the browser what sort of document it is in order for the browser to read it correctly. PHP permits construction of scripts which creates a document header which is suitable for the browser.

PHP Header Function

The PHP header() function is responsible for supplying raw HTTP headers to the browsers. It can be used to redirect the browser to alternative locations. It is important that the redirection script is at the very top of the page in order to prevent any other part of the page from loading. The location: header specifies the target as the argument to the header()function. After this function is called the exit() function halts the parsing of the rest of the code.

The syntax of the header() looks like this

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

Note that header() must be called before any actual output is sent. The output could be normal HTML tags, blank lines in a file or a PHP code.

<html>
<?php
header('Location: http://www.program.com/');
exit;
?>

As you see there is some code before the header function is called. This will result in an error.

Lets take a closer look at the PHP header() function parameters.

  • string– this stands for the header string. There exist two special header clauses. The first one is the header that starts with the string “HTTP/”. This is used to figure out the HTTP status code to send. For instance, if there is a PHP script that handles request for missing files, you may want to ensure that the script generates a proper status code.
<?php
header("HTTP/1.0 404 Not Found");
?>

“Location ” is the second special case. It sends the header back to the browser along with a REDIRECT(302) status code. The latter is not sent if the 201 or a 3xx status code has already been set.

<?php
header("Location: http://www.program.com/");
exit;
?>
  • replace– This is an optional parameter. This specifies whether the header should replace the previous similar header or add another header of the same type. The default behaviour is to replace. However, if you give false as the argument it will force multiple headers of the same type. Take a look at this example.
<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?>
  • http_response_code– In order for this parameter to have an effect, the string parameter should not be empty. This parameter forces the HTTP response to the specified value.

Note that  the header() function does not return a value. To see how XML and PHP come together during web development, check out this course.

Example 1: Use of Header Function Content-Disposition

<?php
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile('original.pdf');
?>

Here the Content-Disposition header supplies a recommended filename and forces the browser to display the save dialog box. In this program, the first line tells the browser that a PDF document will be output. In the second line we give the file the name, downloaded.pdf. Finally, we read the file.

Example 2:  To Cache Directives

 <?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Fri, 27 Jul 2012 07:00:00 GMT");
?>

Often PHP scripts generate dynamic content which should not be cached by the client browser or any proxy caches existing between the server and the client browser. The above code forces many clients and proxies to disable caching. To see more examples of PHP scripts, you can take this course.

Example 3: Program to Redirect a Browser Request

<?php
  if( $_POST["location"] )
  {
     $location = $_POST["location"];
     header( "Location:$location" );
     exit();
  }
?>
<html>
<body>
   <p>Choose a site to visit :</p>
   <form action="<?php $_PHP_SELF ?>" method="POST">
   <select name="location">
      <option value="http://Microsoft.com">
            Microsoft Home Page
      </option>
      <option value="http://www.ibm.com">
            IBM Home Page
      </option>
   </select>
   <input type="submit" />
   </form>
</body>
</html>

$_POST is used to collect form data. In this program, the HTML select tag creates a drop down list with options.Input type=”submit” creates a submit button.

XML Header in PHP

If you plan to output XML content from PHP file, the content-type header needs to be set.  This done so that, your browser knows that you are going to output XML content from the given PHP file instead of the default content-type header.  The default header is content-type: text/html.

<?php
header ("Content-Type:text/xml");
?>
<xml_content>
</xml_content>

Example 4: How to Generate an XML Response from the Server Using PHP

 <?php
header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='UTF-8'?>";
echo "<note>";
echo "<from>Lenny</from>";
echo "<to>Sonia</to>";
echo "<message>Remember my birthday this weekend</message>";
echo "</note>";
?>

Hope this tutorial on XML PHP header article was informative as well as interesting. We recommend that you experiment with the code on your own, to get a better hang of it. Once you’re ready to move on to the next level, you can take this advanced PHP course to help you learn more.