PHP XML Expat Parser

PHP XML Expat Parser
❮ Previous Next ❯

The built-in XML Expat Parser makes it possible to process XML documents in PHP.

The XML Expat Parser
The Expat parser is an event-based parser.

Look at the following XML fraction:

Jani
An event-based parser reports the XML above as a series of three events:

Start element: from
Start CDATA section, value: Jani
Close element: from
The XML Expat Parser functions are part of the PHP core. There is no installation needed to use these functions.

The XML File
The XML file “note.xml” will be used in the example below:

Tove
Jani
Reminder
Don’t forget me this weekend!

Initializing the XML Expat Parser
We want to initialize the XML Expat Parser in PHP, define some handlers for different XML events, and then parse the XML file.

Example
<?php
// Initialize the XML parser
$parser=xml_parser_create();

// Function to use at the start of an element
function start($parser,$element_name,$element_attrs) {
   switch($element_name) {
    case “NOTE”:
    echo “– Note —
“;
    break;
    case “TO”:
    echo “To: “;
    break;
    case “FROM”:
    echo “From: “;
    break;
    case “HEADING”:
    echo “Heading: “;
    break;
    case “BODY”:
    echo “Message: “;
  }
}

// Function to use at the end of an element
function stop($parser,$element_name) {
  echo “
“;
}

// Function to use when finding character data
function char($parser,$data) {
  echo $data;
}

// Specify element handler
xml_set_element_handler($parser,”start”,”stop”);

// Specify data handler
xml_set_character_data_handler($parser,”char”);

// Open XML file
$fp=fopen(“note.xml”,”r”);

// Read data
while ($data=fread($fp,4096)) {
  xml_parse($parser,$data,feof($fp)) or
  die (sprintf(“XML Error: %s at line %d”,
  xml_error_string(xml_get_error_code($parser)),
   xml_get_current_line_number($parser)));
}

// Free the XML parser
xml_parser_free($parser);
?>
Example explained:

Initialize the XML parser with the xml_parser_create() function
Create functions to use with the different event handlers
Add the xml_set_element_handler() function to specify which function will be executed when the parser encounters the opening and closing tags
Add the xml_set_character_data_handler() function to specify which function will execute when the parser encounters character data
Parse the file “note.xml” with the xml_parse() function
In case of an error, add xml_error_string() function to convert an XML error to a textual description
Call the xml_parser_free() function to release the memory allocated with the xml_parser_create() function
More PHP XML Expat Parser
For more information about the PHP Expat functions, visit our PHP XML Parser Reference.

❮ Previous Next ❯

PHP XML DOM Parser

Toggle navigation
TUTORIAL HOME
PHP XML DOM Parser
❮ Previous Next ❯
The built-in DOM parser makes it possible to process XML documents in PHP.

The XML DOM Parser
The DOM parser is a tree-based parser.

Look at the following XML document fraction:

Jani
The DOM sees the XML above as a tree structure:

Level 1: XML Document
Level 2: Root element:
Level 3: Text element: “Jani”
Installation
The DOM parser functions are part of the PHP core. There is no installation needed to use these functions.

The XML File
The XML file below (“note.xml”) will be used in our example:

Tove
Jani
Reminder
Don’t forget me this weekend!

Load and Output XML
We want to initialize the XML parser, load the xml, and output it:

Example
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load(“note.xml”);

print $xmlDoc->saveXML();
?>
The output of the code above will be:

Tove Jani Reminder Don’t forget me this weekend!
If you select “View source” in the browser window, you will see the following HTML:

Tove
Jani
Reminder
Don’t forget me this weekend!

The example above creates a DOMDocument-Object and loads the XML from “note.xml” into it.

Then the saveXML() function puts the internal XML document into a string, so we can output it.

Looping through XML
We want to initialize the XML parser, load the XML, and loop through all elements of the element:

Example
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load(“note.xml”);

$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item) {
  print $item->nodeName . ” = ” . $item->nodeValue . “
“;
}
?>
The output of the code above will be:

#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don’t forget me this weekend!
#text =
In the example above you see that there are empty text nodes between each element.

When XML generates, it often contains white-spaces between the nodes. The XML DOM parser treats these as ordinary elements, and if you are not aware of them, they sometimes cause problems.

If you want to learn more about the XML DOM, please visit our XML tutorial.

❮ Previous Next ❯

PHP – AJAX and PHP

PHP – AJAX and PHP
❮ Previous Next ❯
AJAX is used to create more interactive applications.

AJAX PHP Example
The following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field:

Example
Start typing a name in the input field below:

First name: 
Suggestions:

Example Explained
In the example above, when a user types a character in the input field, a function called “showHint()” is executed.

The function is triggered by the onkeyup event.

Here is the HTML code:

Example

function showHint(str) {
    if (str.length == 0) {
        document.getElementById(“txtHint”).innerHTML = “”;
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById(“txtHint”).innerHTML = this.responseText;
            }
        };
        xmlhttp.open(“GET”, “gethint.php?q=” + str, true);
        xmlhttp.send();
    }
}

Start typing a name in the input field below:

First name: <input type="text" onkeyup="showHint(this.value)">

Suggestions:

Code explanation:

First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function.

However, if the input field is not empty, do the following:

Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a PHP file (gethint.php) on the server
Notice that q parameter is added to the url (gethint.php?q=”+str)
And the str variable holds the content of the input field
The PHP File – “gethint.php”
The PHP file checks an array of names, and returns the corresponding name(s) to the browser:

<?php
// Array with names
$a[] = “Anna”;
$a[] = “Brittany”;
$a[] = “Cinderella”;
$a[] = “Diana”;
$a[] = “Eva”;
$a[] = “Fiona”;
$a[] = “Gunda”;
$a[] = “Hege”;
$a[] = “Inga”;
$a[] = “Johanna”;
$a[] = “Kitty”;
$a[] = “Linda”;
$a[] = “Nina”;
$a[] = “Ophelia”;
$a[] = “Petunia”;
$a[] = “Amanda”;
$a[] = “Raquel”;
$a[] = “Cindy”;
$a[] = “Doris”;
$a[] = “Eve”;
$a[] = “Evita”;
$a[] = “Sunniva”;
$a[] = “Tove”;
$a[] = “Unni”;
$a[] = “Violet”;
$a[] = “Liza”;
$a[] = “Elizabeth”;
$a[] = “Ellen”;
$a[] = “Wenche”;
$a[] = “Vicky”;

// get the q parameter from URL
$q = $_REQUEST[“q”];

$hint = “”;

// lookup all hints from array if $q is different from “”
if ($q !== “”) {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === “”) {
                $hint = $name;
            } else {
                $hint .= “, $name”;
            }
        }
    }
}

// Output “no suggestion” if no hint was found or output correct values
echo $hint === “” ? “no suggestion” : $hint;
?>

❮ Previous Next ❯

PHP – AJAX and MySQL

Toggle navigation
TUTORIAL HOME
PHP – AJAX and MySQL
❮ Previous Next ❯
AJAX can be used for interactive communication with a database.

AJAX Database Example
The following example will demonstrate how a web page can fetch information from a database with AJAX:

Example

Person info will be listed here…
Example Explained – The MySQL Database
The database table we use in the example above looks like this:

id FirstName LastName Age Hometown Job
1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot
Example Explained
In the example above, when a user selects a person in the dropdown list above, a function called “showUser()” is executed.

The function is triggered by the onchange event.

Here is the HTML code:

Example

function showUser(str) {
    if (str == “”) {
        document.getElementById(“txtHint”).innerHTML = “”;
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById(“txtHint”).innerHTML = this.responseText;
            }
        };
        xmlhttp.open(“GET”,”getuser.php?q=”+str,true);
        xmlhttp.send();
    }
}

<select name="users" onchange="showUser(this.value)”>
  Select a person:
  Peter Griffin
  Lois Griffin
  Joseph Swanson
  Glenn Quagmire
 

Person info will be listed here…

Code explanation:

First, check if person is selected. If no person is selected (str == “”), clear the content of txtHint and exit the function. If a person is selected, do the following:

Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The PHP File
The page on the server called by the JavaScript above is a PHP file called “getuser.php”.

The source code in “getuser.php” runs a query against a MySQL database, and returns the result in an HTML table:

table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}

<?php
$q = intval($_GET[‘q’]);

$con = mysqli_connect(‘localhost’,’peter’,’abc123′,’my_db’);
if (!$con) {
    die(‘Could not connect: ‘ . mysqli_error($con));
}

mysqli_select_db($con,”ajax_demo”);
$sql=”SELECT * FROM user WHERE id = ‘”.$q.”‘”;
$result = mysqli_query($con,$sql);

echo “

“;
while($row = mysqli_fetch_array($result)) {
    echo “

“;
    echo “

“;
    echo “

“;
    echo “

“;
    echo “

“;
    echo “

“;
    echo “

“;
}
echo “

Firstname Lastname Age Hometown Job
” . $row[‘FirstName’] . “ ” . $row[‘LastName’] . “ ” . $row[‘Age’] . “ ” . $row[‘Hometown’] . “ ” . $row[‘Job’] . “

“;
mysqli_close($con);
?>

Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:

PHP opens a connection to a MySQL server
The correct person is found
An HTML table is created, filled with data, and sent back to the “txtHint” placeholder

❮ Previous Next ❯

PHP Example – AJAX and XML

Toggle navigation
TUTORIAL HOME
PHP Example – AJAX and XML
❮ Previous Next ❯
AJAX can be used for interactive communication with an XML file.

AJAX XML Example
The following example will demonstrate how a web page can fetch information from an XML file with AJAX:

Example

CD info will be listed here…
Example Explained – The HTML Page
When a user selects a CD in the dropdown list above, a function called “showCD()” is executed. The function is triggered by the “onchange” event:

function showCD(str) {
  if (str==””) {
    document.getElementById(“txtHint”).innerHTML=””;
     return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById(“txtHint”).innerHTML=this.responseText;
     }
  }
  xmlhttp.open(“GET”,”getcd.php?q=”+str,true);
  xmlhttp.send();
}

Select a CD:

Select a CD:
Bob Dylan
Bee Gees
Cat Stevens

CD info will be listed here…

The showCD() function does the following:

Check if a CD is selected
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The PHP File
The page on the server called by the JavaScript above is a PHP file called “getcd.php”.

The PHP script loads an XML document, “cd_catalog.xml”, runs a query against the XML file, and returns the result as HTML:

<?php
$q=$_GET[“q”];

$xmlDoc = new DOMDocument();
$xmlDoc->load(“cd_catalog.xml”);

$x=$xmlDoc->getElementsByTagName(‘ARTIST’);

for ($i=0; $ilength-1; $i++) {
  //Process only element nodes
  if ($x->item($i)->nodeType==1) {
    if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
      $y=($x->item($i)->parentNode);
    }
  }
}

$cd=($y->childNodes);

for ($i=0;$ilength;$i++) {
  //Process only element nodes
  if ($cd->item($i)->nodeType==1) {
    echo(“” . $cd->item($i)->nodeName . “: “);
    echo($cd->item($i)->childNodes->item(0)->nodeValue);
    echo(“
“);
  }
}
?>
When the CD query is sent from the JavaScript to the PHP page, the following happens:

PHP creates an XML DOM object
Find all elements that matches the name sent from the JavaScript
Output the album information (send to the “txtHint” placeholder)

❮ Previous Next ❯

PHP Example – AJAX Live Search

PHP Example – AJAX Live Search
❮ Previous Next ❯
AJAX can be used to create more user-friendly and interactive searches.

AJAX Live Search
The following example will demonstrate a live search, where you get search results while you type.

Live search has many benefits compared to traditional searching:

Results are shown as you type
Results narrow as you continue typing
If results become too narrow, remove characters to see a broader result
Search for a Omega page in the input field below:


The results in the example above are found in an XML file (links.xml). To make this example small and simple, only six results are available.

Example Explained – The HTML Page
When a user types a character in the input field above, the function “showResult()” is executed. The function is triggered by the “onkeyup” event:

function showResult(str) {
  if (str.length==0) {
    document.getElementById(“livesearch”).innerHTML=””;
     document.getElementById(“livesearch”).style.border=”0px”;
     return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById(“livesearch”).innerHTML=this.responseText;
       document.getElementById(“livesearch”).style.border=”1px solid #A5ACB2″;
    }
  }
  xmlhttp.open(“GET”,”livesearch.php?q=”+str,true);
  xmlhttp.send();
}

<input type="text" size="30" onkeyup="showResult(this.value)”>

Source code explanation:

If the input field is empty (str.length==0), the function clears the content of the livesearch placeholder and exits the function.

If the input field is not empty, the showResult() function executes the following:

Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the input field)
The PHP File
The page on the server called by the JavaScript above is a PHP file called “livesearch.php”.

The source code in “livesearch.php” searches an XML file for titles matching the search string and returns the result:

<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load(“links.xml”);

$x=$xmlDoc->getElementsByTagName(‘link’);

//get the q parameter from URL
$q=$_GET[“q”];

//lookup all links from the xml file if length of q>0
if (strlen($q)>0) {
  $hint=””;
  for($i=0; $ilength); $i++) {
    $y=$x->item($i)->getElementsByTagName(‘title’);
    $z=$x->item($i)->getElementsByTagName(‘url’);
    if ($y->item(0)->nodeType==1) {
      //find a link matching the search text
      if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
        if ($hint==””) {
          $hint=”<a href='" .
          $z->item(0)->childNodes->item(0)->nodeValue .
          “‘ target=’_blank’>” .
          $y->item(0)->childNodes->item(0)->nodeValue . ““;
        } else {
          $hint=$hint . “
<a href='" .
          $z->item(0)->childNodes->item(0)->nodeValue .
          “‘ target=’_blank’>” .
          $y->item(0)->childNodes->item(0)->nodeValue . ““;
        }
      }
    }
  }
}

// Set output to “no suggestion” if no hint was found
// or to the correct values
if ($hint==””) {
  $response=”no suggestion”;
} else {
  $response=$hint;
}

//output the response
echo $response;
?>
If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:

Load an XML file into a new XML DOM object
Loop through all elements to find matches from the text sent from the JavaScript
Sets the correct url and title in the “$response” variable. If more than one match is found, all matches are added to the variable
If no matches are found, the $response variable is set to “no suggestion”

❮ Previous Next ❯

PHP Example – AJAX RSS Reader

PHP Example – AJAX RSS Reader
❮ Previous Next ❯

An RSS Reader is used to read RSS Feeds.

AJAX RSS Reader
The following example will demonstrate an RSS reader, where the RSS-feed is loaded into a webpage without reloading:

RSS-feed will be listed here…
Example Explained – The HTML Page
When a user selects an RSS-feed in the dropdown list above, a function called “showRSS()” is executed. The function is triggered by the “onchange” event:

function showRSS(str) {
  if (str.length==0) {
    document.getElementById(“rssOutput”).innerHTML=””;
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById(“rssOutput”).innerHTML=this.responseText;
    }
  }
  xmlhttp.open(“GET”,”getrss.php?q=”+str,true);
  xmlhttp.send();
}

<select onchange="showRSS(this.value)">
Select an RSS-feed:
Google News
NBC News

RSS-feed will be listed here…

The showRSS() function does the following:

Check if an RSS-feed is selected
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The PHP File
The page on the server called by the JavaScript above is a PHP file called “getrss.php”:

<?php
//get the q parameter from URL
$q=$_GET[“q”];

//find out which feed was selected
if($q==”Google”) {
  $xml=(“http://news.google.com/news?ned=us&topic=h&output=rss“);
} elseif($q==”NBC”) {
  $xml=(“http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml“);
}

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

//get elements from “”
$channel=$xmlDoc->getElementsByTagName(‘channel’)->item(0);
$channel_title = $channel->getElementsByTagName(‘title’)
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName(‘link’)
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName(‘description’)
->item(0)->childNodes->item(0)->nodeValue;

//output elements from “”
echo(“

<a href='" . $channel_link
  . “‘>” . $channel_title . ““);
echo(“
“);
echo($channel_desc . “

“);

//get and output “” elements
$x=$xmlDoc->getElementsByTagName(‘item’);
for ($i=0; $i<=2; $i++) {
  $item_title=$x->item($i)->getElementsByTagName(‘title’)
  ->item(0)->childNodes->item(0)->nodeValue;
  $item_link=$x->item($i)->getElementsByTagName(‘link’)
  ->item(0)->childNodes->item(0)->nodeValue;
  $item_desc=$x->item($i)->getElementsByTagName(‘description’)
  ->item(0)->childNodes->item(0)->nodeValue;
  echo (“

<a href='" . $item_link
  . “‘>” . $item_title . ““);
  echo (“
“);
  echo ($item_desc . “

“);
}
?>
When a request for an RSS feed is sent from the JavaScript, the following happens:

Check which feed was selected
Create a new XML DOM object
Load the RSS document in the xml variable
Extract and output elements from the channel element
Extract and output elements from the item elements

❮ Previous Next ❯

PHP Example – AJAX Poll

PHP Example – AJAX Poll
❮ Previous Next ❯
AJAX Poll
The following example will demonstrate a poll where the result is shown without reloading.

Do you like PHP and AJAX so far?
Yes:  
No: 
Example Explained – The HTML Page
When a user chooses an option above, a function called “getVote()” is executed. The function is triggered by the “onclick” event:




function getVote(int) {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById(“poll”).innerHTML=this.responseText;
     }
  }
  xmlhttp.open(“GET”,”poll_vote.php?vote=”+int,true);
  xmlhttp.send();
}





Do you like PHP and AJAX so far?



Yes:


No:







The getVote() function does the following:

Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (vote) is added to the URL (with the value of the yes or no option)
The PHP File
The page on the server called by the JavaScript above is a PHP file called “poll_vote.php”:

<?php
$vote = $_REQUEST[‘vote’];

//get content of textfile
$filename = “poll_result.txt”;
$content = file($filename);

//put content in array
$array = explode(“||”, $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0) {
  $yes = $yes + 1;
}
if ($vote == 1) {
  $no = $no + 1;
}

//insert votes to txt file
$insertvote = $yes.”||”.$no;
$fp = fopen($filename,”w”);
fputs($fp,$insertvote);
fclose($fp);
?>

Result:











Yes:
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>’
height=’20’>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
No:
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>’
height=’20’>
<?php echo(100*round($no/($no+$yes),2)); ?>%


The value is sent from the JavaScript, and the following happens:

Get the content of the “poll_result.txt” file
Put the content of the file in variables and add one to the selected variable
Write the result to the “poll_result.txt” file
Output a graphical representation of the poll result
The Text File
The text file (poll_result.txt) is where we store the data from the poll.

It is stored like this:

0||0
The first number represents the “Yes” votes, the second number represents the “No” votes.

Note: Remember to allow your web server to edit the text file. Do NOT give everyone access, just the web server (PHP).


❮ Previous Next ❯

PHP Examples

Toggle navigation
TUTORIAL HOME
PHP Examples
❮ Previous Next ❯
PHP Syntax

Write text to the output using PHP
Add comments in PHP
Keywords, classes, functions, and user-defined functions ARE NOT case-sensitive
Variable names ARE case-sensitive

Examples explained

PHP Variables

Create different variables
Test global scope (variable outside function)
Test local scope (variable inside function)
Use the global keyword to access a global variable from within a function
Use the $GLOBALS[] array to access a global variable from within a function
Use the static keyword to let a local variable not be deleted after execution of function

Examples explained

PHP Echo and Print

Display strings with the echo command
Display strings and variables with the echo command
Display strings with the print command
Display strings and variables with the print command

Examples explained

PHP Data Types

PHP string
PHP integer
PHP float
PHP array
PHP object
PHP NULL value

Examples explained

PHP Strings

Get the length of a string – strlen()
Count the number of words in a string – str_word_count()
Reverse a string – strrev()
Search for a specific text within a string – strpos()
Replace text within a string – str_replace()

Examples explained

PHP Constants

Case-sensitive constant name
Case-insensitive constant name

Examples explained

PHP Operators

Arithmetic operator: Addition (+)
Arithmetic operator: Subtraction (-)
Arithmetic operator: Multiplication (*)
Arithmetic operator: Division (/)
Arithmetic operator: Modulus (%)
Assignment operator: x = y
Assignment operator: x += y
Assignment operator: x -= y
Assignment operator: x *= y
Assignment operator: x /= y
Assignment operator: x %= y
Comparison operator: Equal (==)
Comparison operator: Identical (===)
Comparison operator: Not equal (!=)
Comparison operator: Not equal ()
Comparison operator: Not identical (!==)
Comparison operator: Greater than (>)
Comparison operator: Less than (<)
Comparison operator: Greater than or equal (>=)
Comparison operator: Less than or equal (<=)
Increment operator: ++$x
Increment operator: $x++
Decrement operator: –$x
Decrement operator: $x–
Logical operator: and
Logical operator: or
Logical operator: xor
Logical operator: && (and)
Logical operator: || (or)
Logical operator: not
String operator: Concatenation of $txt1 and $txt2
String operator: Appends $txt2 to $txt1
Array operator: Union (+)
Array operator: Equality (==)
Array operator: Identity (===)
Array operator: Inequality (!=)
Array operator: Inequality ()
Array operator: Non-identity (!==)

Examples explained

PHP If…Else and Switch Statements

The if statement
The if…else statement
The if…elseif…else statement
The switch statement

Examples explained

PHP While and For Loops

The while loop
The do…while loop
Another do…while loop
The for loop
The foreach loop

Examples explained

PHP Functions

Create a function
Function with one argument
Function with two arguments
Function with default argument value
Function that returns a value

Examples explained

PHP Arrays

Indexed arrays
count() – Return the length of an array
Loop through an indexed array
Associative arrays
Loop through an associative array

Examples explained

PHP Sorting Arrays

sort() – Sort array in ascending alphabetical order
sort() – Sort array in ascending numerical order
rsort() – Sort array in descending alphabetical order
rsort() – Sort array in descending numerical order
asort() – Sort array in ascending order, according to value
ksort() – Sort array in ascending order, according to key
arsort() – Sort array in descending order, according to value
krsort() – Sort array in descending order, according to key

Examples explained

PHP Superglobals

$GLOBAL – Used to access global variables from anywhere in the PHP script
$_SERVER – Holds information about headers, paths, and script locations
$_REQUEST – Used to collect data after submitting an HTML form
$_POST – Used to collect form data after submitting an HTML form. Also used to pass variables
$_GET – Collect data sent in the URL

Examples explained

PHP Form Validation

PHP Form Validation

Example explained

PHP Multidimensional Arrays

Output elements from a multidimensional array
Loop through a multidimensional array

Examples explained

PHP Date and Time

Format today’s date in several ways
Automatically update the copyright year on your website
Output the current time (server time)
Set timezone, then output current time
Create a date and time from a number of parameters in mktime()
Create a date and time from the strtotime() function
Create more dates/times from strtotime()
Output the dates for the next six Saturdays
Output the number of days until 4th of July

Examples explained

PHP Include Files

Use include to include “footer.php” in a page
Use include to include “menu.php” in a page
Use include to include “vars.php” in a page
Use include to include a non-existing file
Use require to include a non-existing file

Examples explained

PHP File Handling

Use readfile() to read a file and write it to the output buffer

Examples explained

PHP File Open/Read/Close

Use fopen(), fread(), and fclose() to open, read, and close a file
Use fgets() to read a single line from a file
Use feof() to read through a file, line by line, until end-of-file is reached
Use fgetc() to read a single character from a file

Examples explained

PHP Cookies

Create and retrieve a cookie
Modify a cookie value
Delete a cookie
Check if cookies are enabled

Examples explained

PHP Sessions

Start a session
Get session variable values
Get all session variable values
Modify a session variable
Destroy a session

Examples explained

PHP Filters

Use filter_list() to list what the PHP filter extension offers
Sanitize a string
Validate an integer
Validate an integer that is 0
Validate an IP address
Sanitize and validate an email address
Sanitize and validate a URL

Examples explained

PHP Select Data From MySQL

Select data with MySQLi (Object-oriented)
Select data with MySQLi (Object-oriented) and put result in an HTML table
Select data with MySQLi (Procedural)
Select data with PDO (+ Prepared statements)

Examples explained

PHP SimpleXML Parser

Use simplexml_load_string() to read XML data from a string
Use simplexml_load_file() to read XML data from a file
Get node values
Get node values of specific elements
Get node values – loop
Get attribute values
Get attribute values – loop
Examples explained

PHP XML Expat Parser

Initialize an XML Expat parser, define some handlers, then parse an XML file

Examples explained


❮ Previous Next ❯

PHP Quiz

PHP Quiz
❮ Previous Next ❯
You can test your PHP skills with Omega’ Quiz.

The Test
The test contains 25 questions and there is no time limit.

The test is not official, it’s just a nice way to see how much you know, or don’t know, about PHP.

Count Your Score
You will get 1 point for each correct answer. At the end of the Quiz, your total score will be displayed. Maximum score is 25 points.

Start the Quiz
Good luck!

Start the Quiz
Omega’ Online Certification
The perfect solution for professionals who need to balance work, family, and career building.

More than 10 000 certificates already issued!

Get Your Certificate »

The HTML Certificate documents your knowledge of HTML.

The CSS Certificate documents your knowledge of advanced CSS.

The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.

The jQuery Certificate documents your knowledge of jQuery.

The PHP Certificate documents your knowledge of PHP and SQL (MySQL).

The XML Certificate documents your knowledge of XML, XML DOM and XSLT.

The Bootstrap Certificate documents your knowledge of the Bootstrap framework.


❮ Previous Next ❯