PHP

PHP Xmlencoder & Xmldecoder Example

In this example we are going to learn how to encode and decode XML (Extensible Markup Language) with PHP. For this example we will use:

  • A computer with PHP >= 5.5 installed
  • notepad++

 
 
 
 

1. What Is XML

XML (Extensible Markup Language) is a markup language like html. It is a syntax for creating data representation languages. XML was designed to store and transport data. It was also designed to be human and machine readable.
 
XML can be divided into two levels. On the first level XML defines a strict but simple syntax. When this syntax is followed, the document is a well formed XML document. On the second level, XML provides a way of placing further restrictions on what can appear in a document. This is done by associating a DTD (Document Type Definition) with an XML document. A DTD is simply a list of things allowed to appear in the XML document.
 
If you are familiar with HTML, then you already have a basic idea of XML. An HTML document is not an XML document since it does not follow all the strict XML syntax rules.

index.xml

<?xml version="1.0" ?>
<games>
<game>
<name> Shadow Clan  </name>
<version>1</version>
<multiplayer>true</multiplayer>
<size w="300" h="300"/>
<description> The Shadow Clan is a group of elite fighters. There mission is simple protect the world from Dark shadow clan </description>
<stage>2</stage>
</game>

<game>
<name> Zombie Escape  </name>
<version>3.2</version>
<multiplayer> false </multiplayer>
<size w="800" h="300"/>
<description> Lagos as been invaded by zombies, lead jane out of the danger zone </description>
<stage>2</stage>
</game>
<game>
<name>Zombie Escape 3 </name>
<version>1.0.2</version>
<multiplayer>false</multiplayer>
<size w="800" h="300"/>
<description> Lagos as been invaded by zombies, lead jane out of the danger zone </description>
<stage> 2 </stage>
</game>
</games>

This is a simple XML file that stores data about the games on a server. The first line identifies this document as an XML file. On this line we can also specify the character encoding used. The document is made up of elements, attributes and textual content. An element starts with a tag, such as <game> and ends with a matching <game>; and the content is between the tags, which can consist of text and nested elements.
Unlike HTML the author of an XML document gets to choose the tags names and attribute names. Below are some rules for creating XML documents

  • XML is case sensitive so  <Title> is not the same as <title>. All XML elements must have closing tags.
  • XML requires a root element (the <game> tag above serves as our root element)
  • Attributes must be quoted
  • Special characters (like &, < , and > signs) must be encoded.

1.1 Decoding XML

In the script below we convert an XML string into PHP data type, specifically an array.

index.php

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:hidden;
	padding:0%;
	border:0%;
	}
	 
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	<title>Php Parser Example</title>
	</head>
	<body>
<?php
$par="<?xml version='1.0' ?>
<game>
<name>Shadow Clan</name>
<version>1</version>
<multiplayer>true</multiplayer>
<size w='300' h='300'/>
<description>The Shadow Clan is a group of elite fighters. There mission is simple protect the world from Dark shadow clan </description>
<stage>2</stage>
</game>";
$p=xml_parser_create();
xml_parse_into_struct($p,$par,$vals,$index);
echo "<p>The index for the array</p>";
print_r($vals);
echo "<p>The values of the xml data</p> ";
print_r($vals);
/*the calls above returns

The index for the array

Array ( [0] => Array ( [tag] => GAME [type] => open [level] => 1 [value] => ) [1] => Array ( [tag] => NAME [type] => complete [level] => 2 [value] => Shadow Clan ) [2] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [3] => Array ( [tag] => VERSION [type] => complete [level] => 2 [value] => 1 ) [4] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [5] => Array ( [tag] => MULTIPLAYER [type] => complete [level] => 2 [value] => true ) [6] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [7] => Array ( [tag] => SIZE [type] => complete [level] => 2 [attributes] => Array ( [W] => 300 [H] => 300 ) ) [8] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [9] => Array ( [tag] => DESCRIPTION [type] => complete [level] => 2 [value] => The Shadow Clan is a group of elite fighters. There mission is simple protect the world from Dark shadow clan ) [10] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [11] => Array ( [tag] => STAGE [type] => complete [level] => 2 [value] => 2 ) [12] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [13] => Array ( [tag] => GAME [type] => close [level] => 1 ) )
The values of the xml data

Array ( [0] => Array ( [tag] => GAME [type] => open [level] => 1 [value] => ) [1] => Array ( [tag] => NAME [type] => complete [level] => 2 [value] => Shadow Clan ) [2] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [3] => Array ( [tag] => VERSION [type] => complete [level] => 2 [value] => 1 ) [4] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [5] => Array ( [tag] => MULTIPLAYER [type] => complete [level] => 2 [value] => true ) [6] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [7] => Array ( [tag] => SIZE [type] => complete [level] => 2 [attributes] => Array ( [W] => 300 [H] => 300 ) ) [8] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [9] => Array ( [tag] => DESCRIPTION [type] => complete [level] => 2 [value] => The Shadow Clan is a group of elite fighters. There mission is simple protect the world from Dark shadow clan ) [10] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [11] => Array ( [tag] => STAGE [type] => complete [level] => 2 [value] => 2 ) [12] => Array ( [tag] => GAME [value] => [type] => cdata [level] => 1 ) [13] => Array ( [tag] => GAME [type] => close [level] => 1 ) )
*/
?>
</body>
</html>

In this example we converted an XML formatted string into a PHP array.
We use the xml_parse_into_struct()  function which takes four parameters. Those are:

  1. Parser: it is required. It specifies the XML parser to be used.
  2. xml: it is required. It specifies the XML data to be parsed.
  3. value: It is Required. It specifies the target array for the XML data.
  4. index: This parameter is optional. It specifies the target array for index data.

The xml_parse_into_struct() function will return 1 if the operation succeeds and 0 for failure. The returned 1 or 0 is not the same as TRUE and FALSE.

index2.php

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:hidden;
	padding:0%;
	border:0%;
	}
	 
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	<title>Php Parser Example</title>
	</head>
	<body>
<?php
$par = file_get_contents("index.xml");// read the contents of a file and store it as a string
$p=xml_parser_create();
xml_parse_into_struct($p,$par,$vals);
echo "<p>The values of the xml data</p> ";
print_r($vals);
?>
</body>
</html>

In the script above we read the XML data from a file and store it in a string, Then we use the xml_parse_into_struct() to process it.

1.2 Encoding PHP String into an XML File

index4.php

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:hidden;
	padding:0%;
	border:0%;
	}
	 
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	<title>Php Parser Example</title>
	</head>
	<body>
<?php
$par=<<<XML
<game>
<name>Shadow Clan</name>
<version>1</version>
<multiplayer>true</multiplayer>
<size w='300' h='300'/>
<description>The Shadow Clan is a group of elite fighters. There mission is simple protect the world from Dark shadow clan </description>
<stage>2</stage>
</game>
XML;
$p= new SimpleXMLElement($par);
$v=$p->asXML("index2.xml");
echo "<h1> Conversion Of String To XML File Done </h1>";

?>
</body>
</html>

In the script above we successfully converted an XML string into an XML file. We used PHP SimpleXMLElement object. The asXML() function returns a well-formed XML string (XML version 1.0) from a SimpleXML object.
We specify an optional parameter to the function ( this represents a file to save our newly formed XML) . If this parameter is specified it writes the data to the file, instead of returning the string.

2 Summary

In this tutorial we learnt about XML. We learnt how to convert an XML file into a PHP array, we also examined how to save a XML string into a properly formatted XML file.

3. Download the source code

Download
You can download the full source code of this example here: phpxmlencoderanddecoder

 

Olayemi Odunayo

I am a programmer and web developer, who has experience in developing websites and writing desktop and mobile applications. I have worked with both schematic and schemaless databases. I am also familiar with third party API and working with cloud servers. I do programming on the client side with Java, JavaScript, html, Ajax and CSS while I use PHP for server side programming.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button