Category: PHP

  • Return Type Declarations

    PHP version 7 extends the scalar type declaration feature to the return value of a function also. As per this new provision, the return type declaration specifies the type of value that a function should return. We can declare the following types for return types −

    • int
    • float
    • bool
    • string
    • interfaces
    • array
    • callable

    To implement the return type declaration, a function is defined as −

    functionmyfunction(type$par1,type$param2):type{# function bodyreturn$val;}

    PHP parser is coercive typing by default. You need to declare “strict_types=1” to enforce stricter verification of the type of variable to be returned with the type used in the definition.

    Example

    In the following example, the division() function is defined with a return type as int.

    <?php
       function division(int $x, int $y): int {
    
      $z = $x/$y;
      return $z;
    } $x=20.5; $y=10; echo "First number: " . $x; echo "\nSecond number: " . $y; echo "\nDivision: " . division($x, $y); ?>

    Since the type checking has not been set to strict_types=1, the division take place even if one of the parameters is a non-integer.

    First number: 20.5
    Second number: 10
    Division: 2
    

    However, as soon as you add the declaration of strict_types at the top of the script, the program raises a fatal error message.

    Fatal error: Uncaught TypeError:division():Argument#1 ($x) must be of type int, float given, called in div.php on line 12 and defined in div.php:3
    Stack trace:#0 div.php(12): division(20.5, 10)#1 {main}
       thrown in div.php on line 3

    VS Code warns about the error even before running the code by displaying error lines at the position of error −

    PHP Return Type Declarations

    Example

    To make the division() function return a float instead of int, cast the numerator to float, and see how PHP raises the fatal error −

    <?php
       // declare(strict_types=1);
       function division(int $x, int $y): int {
    
      $z = (float)$x/$y;
      return $z;
    } $x=20; $y=10; echo "First number: " . $x; echo "\nSecond number: " . $y; echo "\nDivision: " . division($x, $y); ?>

    Uncomment the declare statement at the top and run this code here to check its output. It will show an error −

    First number: 20
    Second number: 10PHP Fatal error:  Uncaught TypeError: division(): Return value must be of type int, float returned in /home/cg/root/14246/main.php:5
    Stack trace:
    #0 /home/cg/root/14246/main.php(13): division()
    #1 {main}
      thrown in /home/cg/root/14246/main.php on line 5
    

  • Scalar Type Declarations

    The feature of providing type hints has been in PHP since version 5. Type hinting refers to the practice of providing the data type of a parameter in the function definition. Before PHP 7, it was possible to use only the array, callable, and class for type hints in a function. PHP 7 onward, you can also insert type hints for parameters of scalar data type such as int, string, bool, etc.

    PHP is a dynamically (and weakly) typed language. Hence, you don’t need to declare the type of the parameter when a function is defined, something which is necessary in a statically type language like C or Java.

    A typical definition of function in PHP is as follows −

    functionaddition($x,$y){echo"First number: $x Second number: $y Addition: ".$x+$y;}

    Here, we assume that the parameters $x and $y are numeric. However, even if the values passed to the function aren’t numeric, the PHP parser tries to cast the variables into compatible type as far as possible.

    If one of the values passed is a string representation of a number, and the second is a numeric variable, PHP casts the string variable to numeric in order to perform the addition operation.

    Example

    Take a look at this following example −

    <?php
       function addition($x, $y) {
    
      echo "First number: " . $x; 
      echo "\nSecond number: " . $y; 
      echo "\nAddition: " . $x+$y;
    } $x="10"; $y=20; addition($x, $y); ?>

    It will produce the following output −

    First number: 10
    Second number: 20
    Addition: 30
    

    However, if $x in the above example is a string that doesn’t hold a valid numeric representation, an error is encountered.

    <?php
       function addition($x, $y) {
    
      echo "First number: " . $x; 
      echo "\nSecond number: " . $y; 
      echo "\nAddition: " . $x+$y;
    } $x="Hello"; $y=20; addition($x, $y); ?>

    Run this code and see how it shows an error.

    Scalar Type Declarations in PHP 7

    A new feature introduced with PHP version 7 allows defining a function with parameters whose data type can be specified within the parenthesis.

    PHP 7 has introduced the following Scalar type declarations −

    • Int
    • Float
    • Bool
    • String
    • Interfaces
    • Array
    • Callable

    Older versions of PHP allowed only the array, callable and class types to be used as type hints. Furthermore, in the older versions of PHP (PHP 5), the fatal error used to be a recoverable error while the new release (PHP 7) returns a throwable error.

    Scalar type declaration is implemented in two modes −

    • Coercive Mode − Coercive is the default mode and need not to be specified.
    • Strict Mode − Strict mode has to be explicitly hinted.

    Coercive Mode

    The addition() function defined in the earlier example can now be re-written by incorporating the type declarations as follows −

    functionaddition(int$x,int$y){echo"First number: $x Second number: $y Addition: ".$x+$y;}

    Note that the parser still casts the incompatible types i.e., string to an int if the string contains an integer as earlier.

    Example

    Take a look at this following example −

    <?php
       function addition(int $x, int $y) {
    
      echo "First number: " . $x;
      echo "\nSecond number: " . $y;
      echo "\nAddition: " . $x+$y;
    } $x="10"; $y=20; echo addition($x, $y); ?>

    It will produce the following output −

    First number: 10
    Second number: 20
    Addition: 30
    

    Obviously, this is because PHP is a weakly typed language, as PHP tries to coerce a variable of string type to an integer. PHP 7 has introduced a strict mode feature that addresses this issue.

    Strict Mode

    To counter the weak type checking of PHP, a strict mode has been introduced. This mode is enabled with a declare statement −

    declare(strict_types=1);

    You should put this statement at the top of the PHP script (usually just below the PHP tag). This means that the strictness of typing for scalars is configured on a per-file basis.

    In the weak mode, the strict_types flag is 0. Setting it to 1 forces the PHP parser to check the compatibility of the parameters and values passed. Add this statement in the above code and check the result. It will show the following error message −

    Fatal error: Uncaught TypeError:addition():Argument#1 ($x) must be of type int, string given, 
    called in add.php on line 12and defined in add.php:4
    
    Stack trace:#0 add.php(12): addition('10', 20)#1 {main}
       thrown in add.php on line 4

    Example

    Here is another example of scalar type declaration in the function definition. The strict mode when enabled raises fatal error if the incompatible types are passed as parameters.

    <?php
       // Strict mode
       // declare(strict_types = 1);
       function sum(int ...$ints) {
    
      return array_sum($ints);
    } print(sum(2, '3', 4.1)); ?>

    Uncomment the declare statement at the top of this code and run it. Now it will produce an error −

    Fatal error: Uncaught TypeError: 
    sum(): Argument #2 must be of type int, string given, 
    called in add.php on line 9 and defined in add.php:4
    Stack trace:
    #0 add.php(9): sum(2, '3', 4.1)
    #1 {main}
       thrown in add.php on line 4
    

    The type-hinting feature is mostly used by IDEs to prompt the user about the expected types of the parameters used in the function declaration. The following screenshot shows the VS Code editor popping up the function prototype as you type.

    PHP Scalar Type Declarations

  • Date & Time

    The built-in library of PHP has a wide range of functions that helps in programmatically handling and manipulating date and time information. Date and Time objects in PHP can be created by passing in a string presentation of date/time information, or from the current system’s time.

    PHP provides the DateTime class that defines a number of methods. In this chapter, we will have a detailed view of the various Date and Time related methods available in PHP.

    The date/time features in PHP implements the ISO 8601 calendar, which implements the current leap-day rules from before the Gregorian calendar was in place. The date and time information is internally stored as a 64-bit number.

    Here are the topics we will cover in this chapter −

    • Getting the Time Stamp with time()
    • Converting a Time Stamp with getdate()
    • Converting a Time Stamp with date()
    • Formatting Date and Time
    • Converting Strings to Dates

    Getting the Time Stamp with time()

    PHP’s time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.

    time():int

    The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.

    <?php
       print time();
    ?>

    Output

    It will produce the following output −

    1699421347
    

    We can convert a time stamp into a form that humans are comfortable with.

    Converting a Time Stamp with getdate()

    The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().

    The following table lists the elements contained in the array returned by getdate().

    Sr.NoKey & DescriptionExample
    1secondsSeconds past the minutes (0-59)20
    2minutesMinutes past the hour (0 – 59)29
    3hoursHours of the day (0 – 23)22
    4mdayDay of the month (1 – 31)11
    5wdayDay of the week (0 – 6)4
    6monMonth of the year (1 – 12)7
    7yearYear (4 digits)1997
    8ydayDay of year ( 0 – 365 )19
    9weekdayDay of the weekThursday
    10monthMonth of the yearJanuary
    110Timestamp948370048

    Now you have complete control over date and time. You can format this date and time in whatever format you want.

    Example

    Take a look at this following example −

    <?php
       $date_array = getdate();
    
       foreach ( $date_array as $key => $val ){
    
      print "$key = $val\n";
    } $formated_date = "Today's date: "; $formated_date .= $date_array['mday'] . "-"; $formated_date .= $date_array['mon'] . "-"; $formated_date .= $date_array['year']; print $formated_date; ?>

    Output

    It will produce the following output −

    seconds = 0
    minutes = 38
    hours = 6
    mday = 8
    wday = 3
    mon = 11
    year = 2023
    yday = 311
    weekday = Wednesday
    month = November
    0 = 1699421880
    Today's date: 8-11-2023
    

    Converting a Time Stamp with date()

    The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.

    date(string$format,?int$timestamp=null):string

    The date() optionally accepts a time stamp if omitted then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.

    The following table lists the codes that a format string can contain −

    Sr.NoFormat & DescriptionExample
    1a‘am’ or ‘pm’ lowercasepm
    2A‘AM’ or ‘PM’ uppercasePM
    3dDay of month, a number with leading zeroes20
    4DDay of week (three letters)Thu
    5FMonth nameJanuary
    6hHour (12-hour format – leading zeroes)12
    7HHour (24-hour format – leading zeroes)22
    8gHour (12-hour format – no leading zeroes)12
    9GHour (24-hour format – no leading zeroes)22
    10iMinutes ( 0 – 59 )23
    11jDay of the month (no leading zeroes20
    12l (Lower ‘L’)Day of the weekThursday
    13LLeap year (‘1’ for yes, ‘0’ for no)1
    14mMonth of year (number – leading zeroes)1
    15MMonth of year (three letters)Jan
    16rThe RFC 2822 formatted dateThu, 21 Dec 2000 16:01:07 +0200
    17nMonth of year (number – no leading zeroes)2
    18sSeconds of hour20
    19UTime stamp948372444
    20yYear (two digits)06
    21YYear (four digits)2006
    22zDay of year (0 – 365)206
    23ZOffset in seconds from GMT+5

    Example

    Take a look at this following example −

    <?php
       print date("m/d/y G.i:s \n", time()) . PHP_EOL;
       print "Today is ";
       print date("j of F Y, \a\\t g.i a", time());
    ?>

    Output

    It will produce the following output −

    11/08/23 11.23:08
    
    Today is 8 2023f November 2023, at 11.23 am
    

    Formatting Date and Time

    You can format the date and time in different ways with the help of the date() function. Here are some examples −

    Have a look at this following example −

    <?php
       echo date("d/m/Y"); 
       echo "\n";
       echo date("l, F j, Y"); 
    ?>

    Output

    It will create the below output −

    17/02/2025
    Monday, February 17, 2025
    

    Converting Strings to Dates

    The strtotime() function converts a string-formatted date to a timestamp. This is useful when manipulating and computing dates.

    Have a look at the below example showing the usage of strtotime() function −

    Open Compiler

    <?php
       $date = "2025-02-17";
       $timestamp = strtotime($date);
       echo $timestamp; 
    ?>

    Output

    It will produce the below output −

    1739750400
    

    Hope you have good understanding on how to format date and time according to your requirement. For your reference a complete list of all the date and time functions is given in PHP Date & Time Functions.

  • MySQL Login

    MySQL is a popular choice as a backend database for PHP powered web applications. In this chapter, we shall learn to develop a login page for a PHP application that authenticates the given username and password.

    You should have a web server having PHP and MySQL installed for experimenting with the example discussed in this chapter. The bundled binaries of Apache, PHP and MySQL (MariaDB) in the form of XAMPP for your operating system can be easily installed.

    Before running the example code, you should have a MySQL database called mydb in which there must be a table called admin. You can use following SQL script to create the table and insert a test data

    usemydb;CREATETABLEadmin(usernamevarchar(10)NOTNULL,passcodevarchar(10)NOTNULL)ENGINE=InnoDB DEFAULTCHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;INSERTINTOadmin(username,passcode)VALUES('guest','abc123'),('manager','secret'),('user','test');ALTERTABLEadminADDPRIMARYKEY(username);COMMIT;

    The first part of PHP login application is to establish database connection object. We use myqli API to obtain connection object. Save following code as “config.php”

    Config.php

    <?php
       define('DB_SERVER', 'localhost');
       define('DB_USERNAME', 'root');
       define('DB_PASSWORD', '');
       define('DB_DATABASE', 'mydb');
       $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
    ?>

    This PHP script is called inside the login script. It presents the user with a HTML form to enter username and password. In case the form is submitted, PHP runs a SELECT query to retrieve a row in the admin table where the username and passcode matches with the user inputs.

    $myusername=mysqli_real_escape_string($db,$_POST['username']);$mypassword=mysqli_real_escape_string($db,$_POST['password']);$sql="SELECT * FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";$result=mysqli_query($db,$sql);$row=mysqli_num_rows($result);

    If the row count is one, it indicates that the username and the password entered matches. The username is save to the $_SESSION variable and the browser is directed to welcome.php script.

    Login.php

    Save the following code as “login.php” −

    <?php
       include("config.php");
       session_start();
       $error='';
       if($_SERVER["REQUEST_METHOD"] == "POST") {
       
    
      // username and password sent from form 
      $myusername = mysqli_real_escape_string($db,$_POST['username']);
      $mypassword = mysqli_real_escape_string($db,$_POST['password']); 
      $sql = "SELECT * FROM admin WHERE username = '$myusername' and passcode = '$mypassword'";
      $result = mysqli_query($db,$sql);      
      $row = mysqli_num_rows($result);      
      $count = mysqli_num_rows($result);
      if($count == 1) {
         // session_register("myusername");
         $_SESSION['login_user'] = $myusername;
         header("location: welcome.php");
      } else {
         $error = "Your Login Name or Password is invalid";
      }
    } ?><html><head><title>Login Page</title><style type = "text/css">
      body {
         font-family:Arial, Helvetica, sans-serif;
         font-size:14px;
      }
      label {
         font-weight:bold;
         width:100px;
         font-size:14px;
      }
      .box {
         border:#666666 solid 1px;
      }
    </style></head><body bgcolor = "#FFFFFF"><div align = "center"><div style = "width:300px; border: solid 1px #333333; " align = "left"><div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div><div style = "margin:30px"><form action = "" method = "post"><label>UserName :</label><input type = "text" name = "username" class = "box"/><br /><br /><label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br /><input type = "submit" value = " Submit "/><br /></form><div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div></div></div></div></body></html>

    Session.php

    The following is thesession.phpcode file. It checks if the session variable is set; then the user credentials will be assigned to the$login_sessionvariable. If not, the user is redirected back to thelogin.phpfile.

    <?php
       // Start the session
       session_start();
    
       if(!isset($_SESSION['login_user'])){
    
      header("location: login.php");
      die();
    } $login_session = $_SESSION['login_user']; ?>

    Welcome.php

    The “welcome.php” script gets invoked when the user is authenticated. It reads the session variable to display a welcome message.

    <?php
       include('session.php');
    ?><html><head><title>Welcome </title></head><body><h1>Welcome <?php echo $login_session; ?></h1><h2><a href = "logout.php">Sign Out</a></h2></body></html>

    Logout.php

    Finally, the logout script removes the destroys the session and redirects the user to the login page.

    <?php
       session_start();
    
       if(session_destroy()) {
    
      header("Location: login.php");
    } ?>

    To start the login application, visit “http://localhost/login.php”

    PHP MySQL Login 1

    Enter the username and password. On pressing the submit button, these inputs are checked against the rows in admin table. On success, you get the following message −

    PHP MySQL Login 2

    If the query doesnt fetch any matching row, the error message is displayed as follows −

    PHP MySQL Login 3

  • Paypal Integration

    PayPal is a payment processing system. We can integrate PayPal with websites by using with PHP.

    PayPal Integration File System

    PayPal integration file system included four files as shown below −

    • constants.php − This file includes the API user name, password and signature.
    • CallerService.php − This file includes the PayPal Services, which are used to call PayPal services.
    • confirmation.php − This file includes a form with minimum fields required to make payment process and it will return payment success or failure.
    • PayPal_entry.php − This page has used to send the user the data to PayPal. It acts as an adapter between PayPal and user form.

    The user has to download a PayPal SDK file from here and exact a zip file. The zip file contains four PHP files. We don’t need to change any file except “constants.php”.

    constants.php

    The “constants.php” file contains code as shown below −

    <?php
       define('API_USERNAME', 'YOUR USER NAME HERE');
       define('API_PASSWORD', 'YOUR PASSWORD HERE');
       define('API_SIGNATURE', 'YOUR API SIGNATURE HERE');
       define('API_ENDPOINT', 'https://api-3t.paypal.com/nvp');
       define('USE_PROXY',FALSE);
       define('PROXY_HOST', '127.0.0.1');
       define('PROXY_PORT', '808');
       define('PAYPAL_URL', 'https://www.PayPal.com/webscr&cmd=_express-checkout&token=');
       define('VERSION', '53.0');
    ?>

    The user will declare the username, password and signature in the above syntax which are placed in “constants.php”.

    This is an experimental example so the last amount will be added to sandbox’s account.

  • Facebook Login

    Users can be asked to log into a web application with the help of Social media login, also called SSO. This way users need not create a new account. Instead, users can use their existing social media account information to log in. Some examples of social media login include: Google, Facebook, LinkedIn, Apple.

    In this chapter, we shall explain how to activate logging into a PHP application with Facebook credentials.

    The first step to add Facebook login feature is to create a Facebook app. Visit https://developers.facebook.com/apps/creation/ and sign in with your Facebook account.

    PHP Facebook Login 1

    Next, enter the name of the Facebook app you want to create −

    PHP Facebook Login 2

    Go in the App settings and obtain Application ID and secret code −

    PHP Facebook Login 3

    Select platform as website −

    PHP Facebook Login 4

    Next, you need to set Up Facebook SDK in PHP. Download the Facebook SDK for PHP from “https://packagist.org/packages/facebook/php-sdk” or use composer: composer require “facebook/graph-sdk-v5”. Extract the SDK files to a directory accessible by your PHP application.

    To configure Facebook SDK in PHP Code, include the Facebook SDK autoloader in your PHP file: require_once __DIR__ . ‘/vendor/autoload.php’;

    Set up your app’s access token and app secret −

    $app_id='YOUR_APP_ID';$app_secret='YOUR_APP_SECRET';

    Next, create Facebook Login Button. Create an HTML button and add the Facebook login JavaScript SDK to trigger the login flow −

    <button id="facebook-login-button">Login with Facebook</button>

    Include the Facebook JavaScript SDK −

    <script src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v13.0&appId=YOUR_APP_ID&autoLogApp=true" async defer></script>

    Create a PHP script to handle the Facebook login callback −

    <?php
       session_start();
    
       $fb = new Facebook\Facebook([
    
      'app_id' =&gt; $app_id,
      'app_secret' =&gt; $app_secret,
      'default_graph_version' =&gt; 'v13.0',
    ]); $helper = $fb->getRedirectLoginHelper(); $accessToken = $helper->getAccessToken(); if ($accessToken) {
      // User is logged in, handle their data
      $user = $fb-&gt;get('/me', ['fields' =&gt; 'id,name,email']);
      $_SESSION['user_data'] = $user;
      header('Location: profile.php');
    } else {
      // User is not logged in, redirect to login page
      $loginUrl = $helper-&gt;getLoginUrl(['scope' =&gt; 'public_profile,email']);
      header('Location: ' . $loginUrl);
    } ?>

    After successful login, store user data in the session and redirect to a protected page. On protected pages, check the session for user data to verify access.

  • Login Example

    A typical PHP web application authenticates the user before logging in, by asking his credentials such as username and password. The credentials are then checked against the user data available with the server. In this example, the user data is available in the form of an associative array. The following PHP Login script is explained below −

    HTML Form

    The HTML part of the code presents a simple HTML form, that accepts username and password, and posts the data to itself.

    <form action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post"><div><label for="username">Username:</label><input type="text" name="username" id="name"></div><div><label for="password">Password:</label><input type="password" name="password" id="password"></div><section style="margin-left:2rem;"><button type="submit" name="login">Login</button></section></form>

    PHP Authentication

    The PHP script parses the POST data, and checks if the username is present in the users array. If found, it further checks whether the password corresponds to the registered user in the array

    <?php
       if (array_key_exists($user, $users)) {
    
      if ($users[$_POST['username']]==$_POST['password']) {
         $_SESSION['valid'] = true;
         $_SESSION['timeout'] = time();
         $_SESSION['username'] = $_POST['username'];
         $msg = "You have entered correct username and password";
      } else { 
         $msg = "You have entered wrong Password"; 
      }
    } else {
      $msg = "You have entered wrong user name";
    } ?>

    The username and the appropriate message is added to the $_SESSION array. The user is prompted with a respective message, whether the credentials entered by him are correct or not.

    The Complete Code

    Here is the complete code −

    Login.php

    <?php
       ob_start();
       session_start();
    ?><html lang = "en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="loginstyle.css"><title>Login</title></head><body><h2 style="margin-left:10rem; margin-top:5rem;">Enter Username and Password</h2><?php
    
      $msg = '';
      $users = ['user'=&gt;"test", "manager"=&gt;"secret", "guest"=&gt;"abc123"];
      if (isset($_POST['login']) &amp;&amp; !empty($_POST['username']) 
      &amp;&amp; !empty($_POST['password'])) {
         $user=$_POST['username'];                  
         if (array_key_exists($user, $users)){
            if ($users[$_POST['username']]==$_POST['password']){
               $_SESSION['valid'] = true;
               $_SESSION['timeout'] = time();
               $_SESSION['username'] = $_POST['username'];
               $msg = "You have entered correct username and password";
            }
            else {
               $msg = "You have entered wrong Password";
            }
         }
         else {
            $msg = "You have entered wrong user name";
         }
      }
    ?><h4 style="margin-left:10rem; color:red;"><?php echo $msg; ?></h4><br/><br/><form action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post"><div><label for="username">Username:</label><input type="text" name="username" id="name"></div><div><label for="password">Password:</label><input type="password" name="password" id="password"></div><section style="margin-left:2rem;"><button type="submit" name="login">Login</button></section></form><p style="margin-left: 2rem;"><a href = "logout.php" tite = "Logout">Click here to clean Session.</a></p></div></body></html>

    Logout.php

    To logout, the user clicks on the link to logout.php

    <?php
       session_start();
       unset($_SESSION["username"]);
       unset($_SESSION["password"]);
       
       echo '<h4>You have cleaned session</h4>';
       header('Refresh: 2; URL = login.php');
    ?>

    Start the application by entering “http://localhost/login.php”. Here are the different scenarios −

    Correct Username and Password

    PHP Login Example 1

    Incorrect Password

    PHP Login Example 2

    Incorrect Username

    PHP Login Example 3

    When the user clicks the link at the bottom, the session variables are removed, and the login screen reappears.

  • DOM Parser Example

    The DOM extension in PHP comes with extensive functionality with which we can perform various operations on XML and HTML documents. We can dynamically construct a DOM object, load a DOM document from a HTML file or a string with HTML tag tree. We can also save the DOM document to a XML file, or extract the DOM tree from a XML document.

    The DOMDocument class is one the most important classes defined in the DOM extension.

    $obj=newDOMDocument($version="1.0",$encoding="")

    It represents an entire HTML or XML document; serves as the root of the document tree. The DOMDocument class includes definitions of a number of static methods, some of which are introduced here −

    Sr.NoMethods & Description
    1createElementCreate new element node
    2createAttributeCreate new attribute
    3createTextNodeCreate new text node
    4getElementByIdSearches for an element with a certain id
    5getElementsByTagNameSearches for all elements with given local tag name
    6loadLoad XML from a file
    7loadHTMLLoad HTML from a string
    8loadHTMLFileLoad HTML from a file
    9loadXMLLoad XML from a string
    10saveDumps the internal XML tree back into a file
    11saveHTMLDumps the internal document into a string using HTML formatting
    12saveHTMLFileDumps the internal document into a file using HTML formatting
    13saveXMLDumps the internal XML tree back into a string

    Example

    Let us use the following HTML file for this example −

    <html><head><title>Tutorialspoint</title></head><body><h2>Course details</h2><table border = "0"><tbody><tr><td>Android</td><td>Gopal</td><td>Sairam</td></tr><tr><td>Hadoop</td><td>Gopal</td><td>Satish</td></tr><tr><td>HTML</td><td>Gopal</td><td>Raju</td></tr><tr><td>Web technologies</td><td>Gopal</td><td>Javed</td></tr><tr><td>Graphic</td><td>Gopal</td><td>Satish</td></tr><tr><td>Writer</td><td>Kiran</td><td>Amith</td></tr><tr><td>Writer</td><td>Kiran</td><td>Vineeth</td></tr></tbody></table></body></html>

    We shall now extract the Document Object Model from the above HTML file by calling the loadHTMLFile() method in the following PHP code −

    <?php 
    
       /*** a new dom object ***/ 
       $dom = new domDocument; 
    
       /*** load the html into the object ***/ 
       $dom->loadHTMLFile("hello.html");
    
       /*** discard white space ***/ 
       $dom->preserveWhiteSpace = false; 
    
       /*** the table by its tag name ***/ 
       $tables = $dom->getElementsByTagName('table'); 
    
       /*** get all rows from the table ***/ 
       $rows = $tables[0]->getElementsByTagName('tr'); 
    
       /*** loop over the table rows ***/ 
       foreach ($rows as $row) {
       
    
      /*** get each column by tag name ***/ 
      $cols = $row-&gt;getElementsByTagName('td'); 
      /*** echo the values ***/ 
      echo 'Designation: '.$cols-&gt;item(0)-&gt;nodeValue.'&lt;br /&gt;'; 
      echo 'Manager: '.$cols-&gt;item(1)-&gt;nodeValue.'&lt;br /&gt;'; 
      echo 'Team: '.$cols-&gt;item(2)-&gt;nodeValue; 
      echo '&lt;hr /&gt;'; 
    } ?>
  • SAX Parser Example

    PHP has the XML parser extension enabled by default in the php.ini settings file. This parser implements SAX API, which is an event-based parsing algorithm.

    An event-based parser doesnt load the entire XML document in the memory. instead, it reads in one node at a time. The parser allows you to interact with in real time. Once you move onto the next node, the old one is removed from the memory.

    SAX based parsing mechanism is faster than the tree based parsers. PHP library includes functions to handle the XML events, as explained in this chapter.

    The first step in parsing a XML document is to have a parser object, with xml_parse_create() function

    xml_parser_create(?string$encoding=null):XMLParser

    This function creates a new XML parser and returns an object of XMLParser to be used by the other XML functions.

    The xml_parse() function starts parsing an XML document

    xml_parse(XMLParser$parser,string$data,bool$is_final=false):int

    xml_parse() parses an XML document. The handlers for the configured events are called as many times as necessary.

    The XMLParser extension provides different event handler functions.

    xml_set_element_handler()

    This function sets the element handler functions for the XML parser. Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags.

    xml_set_element_handler(XMLParser$parser,callable$start_handler,callable$end_handler):true

    The start_handler() function is called when a new XML element is opened. end_handler() function is called when an XML element is closed.

    xml_set_character_data_handler()

    This function sets the character data handler function for the XML parser parser. Character data is roughly all the non-markup contents of XML documents, including whitespace between tags.

    xml_set_character_data_handler(XMLParser$parser,callable$handler):true

    xml_set_processing_instruction_handler()

    This function sets the processing instruction (PI) handler function for the XML parser parser. <?php ?> is a processing instruction, where php is called the “PI target”. The handling of these are application-specific.

    xml_set_processing_instruction_handler(XMLParser$parser,callable$handler):true

    processing instruction has the following format −

    <?target
       data
    ?>

    xml_set_default_handler()

    This function sets the default handler function for the XML parser parser. What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler.

    xml_set_default_handler(XMLParser$parser,callable$handler):true

    Example

    The following example demonstrates the use of SAX API for parsing the XML document. We shall use the SAX.xml as below −

    <?xml version = "1.0" encoding = "utf-8"?><tutors><course><name>Android</name><country>India</country><email>[email protected]</email><phone>123456789</phone></course><course><name>Java</name><country>India</country><email>[email protected]</email><phone>123456789</phone></course><course><name>HTML</name><country>India</country><email>[email protected]</email><phone>123456789</phone></course></tutors>

    Example

    The PHP code to parse the above document is given below. It opens the XML file and calls xml_parse() function till its end of file is reached. The event handlers store the data in tutors array. Then the array is echoed element wise.

    <?php
    
       // Reading XML using the SAX(Simple API for XML) parser 
       $tutors   = array();
       $elements   = null;
    
       // Called to this function when tags are opened 
       function startElements($parser, $name, $attrs) {
    
      global $tutors, $elements;
      if(!empty($name)) {
         if ($name == 'COURSE') {
            // creating an array to store information
            $tutors []= array();
         }
         $elements = $name;
      }
    } // Called to this function when tags are closed function endElements($parser, $name) {
      global $elements;
      if(!empty($name)) {
         $elements = null;
      }
    } // Called on the text between the start and end of the tags function characterData($parser, $data) {
      global $tutors, $elements;
      if(!empty($data)) {
         if ($elements == 'NAME' || $elements == 'COUNTRY' ||  $elements == 'EMAIL' ||  $elements == 'PHONE') {
            $tutors[count($tutors)-1][$elements] = trim($data);
         }
      }
    } $parser = xml_parser_create(); xml_set_element_handler($parser, "startElements", "endElements"); xml_set_character_data_handler($parser, "characterData"); // open xml file if (!($handle = fopen('sax.xml', "r"))) {
      die("could not open XML input");
    } while($data = fread($handle, 4096)) {
      xml_parse($parser, $data);  
    } xml_parser_free($parser); $i = 1; foreach($tutors as $course) {
      echo "course No - ".$i. '&lt;br/&gt;';
      echo "course Name - ".$course['NAME'].'&lt;br/&gt;';
      echo "Country - ".$course['COUNTRY'].'&lt;br/&gt;';
      echo "Email - ".$course['EMAIL'].'&lt;br/&gt;';
      echo "Phone - ".$course['PHONE'].'&lt;hr/&gt;'; 
      $i++; 
    } ?>
  • Simple XML Parser

    The SimpleXML extension of PHP provides a very simple and easy to use toolset to convert XML to an object that can be processed with normal property selectors and array iterators. It is a tree_based parser, and works well with simple XML files, but may face issues when working with larger and complex XML documents.

    The following functions are defined in SimpleXML extension −

    simplexml_load_file

    The simplexml_load_file() function interprets an XML file into an object −

    simplexml_load_file(string$filename,?string$class_name=SimpleXMLElement::class,int$options=0,string$namespace_or_prefix="",bool$is_prefix=false):SimpleXMLElement|false

    A well-formed XML document in the given file is converted into an object.

    The filename parameter is a string representing the XML file to be parsed. class_name is the optional parameter. It specifies the class whose object will be returned by the function. The function returns an object of class SimpleXMLElement with properties containing the data held within the XML document, or false on failure.

    Example

    Take a look at the following example −

    <?php
       $xml = simplexml_load_file("test.xml") or die("Error: Cannot create object");
       print_r($xml);
    ?>

    It will produce the following output −

    SimpleXMLElement Object
    (
       [Course] => Android
       [Subject] => Android
       [Company] => TutorialsPoint
       [Price] => $10
    )
    

    simplexml_load_string

    The simplexml_load_string() function interprets an XML file into an object.

    simplexml_load_string(string$filename,?string$class_name=SimpleXMLElement::class,int$options=0,string$namespace_or_prefix="",bool$is_prefix=false):SimpleXMLElement|false

    A well-formed XML document in the given string is converted into an object.

    The $data parameter is a string representing the XML document to be parsed. class_name is the optional parameter. It specifies the class whose object will be returned by the function. The function returns an object of class SimpleXMLElement with properties containing the data held within the XML document, or false on failure.

    Example

    Take a look at the following example −

    <?php
       $data = "<?xml version = '1.0' encoding = 'UTF-8'?>   
       <note>
    
      &lt;Course&gt;Android&lt;/Course&gt;
      &lt;Subject&gt;Android&lt;/Subject&gt;
      &lt;Company&gt;TutorialsPoint&lt;/Company&gt;
      &lt;Price&gt;$10&lt;/Price&gt;
    </note>"; $xml = simplexml_load_string($data) or die("Error: Cannot create object"); print_r($xml); ?>

    It will produce the following output −

    SimpleXMLElement Object
    (
       [Course] => Android
       [Subject] => Android
       [Company] => TutorialsPoint
       [Price] => $10
    )
    

    simplexml_import_dom

    The simplexml_import_dom() function constructs a SimpleXMLElement object from a DOM node.

    simplexml_import_dom(SimpleXMLElement|DOMNode$node,?string$class_name=SimpleXMLElement::class):?SimpleXMLElement

    This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element.

    The node parameter is a DOM Element node. The optional class_name may be given so that simplexml_import_dom() will return an object of the specified sub class of the SimpleXMLElement class. The value returned by this function is a SimpleXMLElement or null on failure.

    Example

    Take a look at the following example −

    <?php
       $dom = new DOMDocument;
       $dom->loadXML('<books><book><title>PHP Handbook</title></book></books>');
       if (!$dom) {
    
      echo 'Error while parsing the document';
      exit;
    } $s = simplexml_import_dom($dom); echo $s->book[0]->title; ?>

    It will produce the following output −

    PHP Handbook
    

    Get the Node Values

    The following code shows how to get the node values from an XML file and the XML should be as follows −

    <?xml version = "1.0" encoding = "utf-8"?><tutorialspoint><course category = "JAVA"><title lang = "en">Java</title><tutor>Gopal</tutor><duration></duration><price>$30</price></course><course category = "HADOOP"><title lang = "en">Hadoop</title>.
    
      &lt;tutor&gt;Satish&lt;/tutor&gt;&lt;duration&gt;3&lt;/duration&gt;&lt;price&gt;$50&lt;/price&gt;&lt;/course&gt;&lt;course category = "HTML"&gt;&lt;title lang = "en"&gt;html&lt;/title&gt;&lt;tutor&gt;raju&lt;/tutor&gt;&lt;duration&gt;5&lt;/duration&gt;&lt;price&gt;$50&lt;/price&gt;&lt;/course&gt;&lt;course category = "WEB"&gt;&lt;title lang = "en"&gt;Web Technologies&lt;/title&gt;&lt;tutor&gt;Javed&lt;/tutor&gt;&lt;duration&gt;10&lt;/duration&gt;&lt;price&gt;$60&lt;/price&gt;&lt;/course&gt;&lt;/tutorialspoint&gt;</pre>

    Example

    PHP code should be as follows −

    <?php
       $xml = simplexml_load_file("books.xml") or die("Error: Cannot create object");
    
       foreach($xml->children() as $books) { 
    
      echo $books-&gt;title . "&lt;br&gt; "; 
      echo $books-&gt;tutor . "&lt;br&gt; "; 
      echo $books-&gt;duration . "&lt;br&gt; ";
      echo $books-&gt;price . "&lt;hr&gt;"; 
    } ?>

    It will produce the following output −

    Java
    Gopal
    
    $30
    ________________________________________
    Hadoop
    Satish
    3
    $50
    ________________________________________
    html
    raju
    5
    $50
    ________________________________________
    Web Technologies
    Javed
    10
    $60
    ________________________________________