Verification: a143cc29221c9be0

Php add element to object

What is XML?

XML is the acronym for Extensible Markup Language.

XML is used to structure, store and transport data from one system to another.

XML is similar to HTML.

It uses opening and closing tags.

Unlike HTML, XML allows users to define their own tags.

In this tutorial, you will learn-

  • What is DOM?
  • XML Parsers
  • Why use XML?
  • XML Document Example
  • How to Read XML using PHP
  • How to Create an XML document using PHP

What is DOM?

DOM is the acronym for Document Object Model.

It’s a cross platform and language neutral standard that defines how to access and manipulate data in;

  • HTML
  • XHTML
  • XML

DOM XML is used to access and manipulate XML documents. It views the XML document as a tree-structure.

XML Parsers

An XML parser is a program that translates the XML document into an XML Document Object Model (DOM) Object.

The XML DOM Object can then be manipulated using JavaScript, Python, and PHP etc.

The keyword CDATA which is the acronym for (Unparsed) Character Data is used to ignore special characters such as “” when parsing an XML document.

Why use XML?

  • Web services such as SOAP and REST use XML format to exchange information. Learning what XML is and how it works will get you competitive advantage as a developer since modern applications make heavy use of web services.
  • XML documents can be used to store configuration settings of an application
  • It allows you to create your own custom tags which make it more flexible.

XML Document example

Let’s suppose that you are developing an application that gets data from a web service in XML format.

Below is the sample of how the XML document looks like.



        

            Joe Paul

            CEO

        

        

            Tasha Smith

            Finance Manager

        

  HERE,

  • ” specifies the xml version to be used and encoding
  • ” is the root element.
  •  “” are the child elements of administration and sales respectively.

How to Read XML using PHP

Let’s now write the code that will read the employees XML document and display the results in a web browser. Index.php

Employees Listing';

$list = $xml->record;

for ($i = 0; $i Man no: ' . $list[$i]->attributes()->man_no . '
';     echo 'Name: ' . $list[$i]->name . '
';     echo 'Position: ' . $list[$i]->position . '

'; } ?>

  HERE,

  • “$xml = simplexml_load_file('employees.xml');” uses the simplexml_load_file function to load the file name employees.xml and assign the contents to the array variable $xml.
  • “$list = $xml->record;” gets the contents of the record node.
  •  “for ($i = 0; $i
  • “$list[$i]->attributes()->man_no;” reads the man_no attribute of the element
  • “$list[$i]->name;” reads the value of the name child element
  • “$list[$i]->position;” reads the value of the position child element

Testing our application

Assuming you saved the file index.php in phptus/xml folder, browse to the URL http://localhost/phptuts/xml/index.php

How to Create an XML document using PHP

We will now look at how to create an XML document using PHP.

We will use the example above in the DOM tree diagram.

The following code uses the PHP built in class DOMDocument to create an XML document.

encoding = 'utf-8';

		$dom->xmlVersion = '1.0';

		$dom->formatOutput = true;

	$xml_file_name = 'movies_list.xml';

		$root = $dom->createElement('Movies');

		$movie_node = $dom->createElement('movie');

		$attr_movie_id = new DOMAttr('movie_id', '5467');

		$movie_node->setAttributeNode($attr_movie_id);

	$child_node_title = $dom->createElement('Title', 'The Campaign');

		$movie_node->appendChild($child_node_title);

		$child_node_year = $dom->createElement('Year', 2012);

		$movie_node->appendChild($child_node_year);

	$child_node_genre = $dom->createElement('Genre', 'The Campaign');

		$movie_node->appendChild($child_node_genre);

		$child_node_ratings = $dom->createElement('Ratings', 6.2);

		$movie_node->appendChild($child_node_ratings);

		$root->appendChild($movie_node);

		$dom->appendChild($root);

	$dom->save($xml_file_name);

	echo "$xml_file_name has been successfully created";
?>

  HERE,

  • “$dom = new DOMDocument();” creates an instance of DOMDocument class.
  • “$dom->encoding = 'utf-8';” sets the document encoding to utf-8
  • “$dom->xmlVersion = '1.0';” specifies the version number 1.0
  • “$dom->formatOutput = true;” ensures that the output is well formatted
  • “$root = $dom->createElement('Movies');” creates the root node named Movies
  • “$attr_movie_id = new DOMAttr('movie_id', '5467');” defines the movie id attribute of Movies node
  • “$child_node_element_name = $dom->createElement('ElementName', 'ElementValue')” creates the child node of Movies node. ElementName specifies the name of the element e.g. Title. ElementValue sets the child node value e.g. The Campaign.
  • “$root->appendChild($movie_node);” appends the movie_node elements to the root node Movies
  • “$dom->appendChild($root);” appends the root node to the XML document.
  • “$dom->save($xml_file_name);” saves the XML file in the root directory of the web server.
  • “echo '' . $xml_file_name . ' has been successfully created';” creates the link to the XML file.

Testing our application

Assuming you saved the file create_movies_list in phptuts/xml folder, browse to the URL http://localhost/phptuts/xml/create_movies_list.php

Click on movies_list_xml link

What is a PHP Array?

A PHP array is a variable that stores more than one piece of related data in a single variable.

Think of an array as a box of chocolates with slots inside.

The box represents the array itself while the spaces containing chocolates represent the values stored in the arrays.

The diagram below illustrates the above syntax.
 

In this tutorial, you will learn-

  • Numeric Arrays
  • PHP Associative Array
  • PHP Multi-dimensional arrays
  • PHP Array operators

Numeric Arrays

Numeric arrays use number as access keys.

An access key is a reference to a memory slot in an array variable.

The access key is used whenever we want to read or assign a new value an array element.

Below is the syntax for creating numeric array in php. Array Example

Or

 value, …);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “[n]” is the access index number of the element
  • “value” is the value assigned to the array element.

Let’s now look at an example of a numeric array.

Suppose we have 5 movies that we want to store in array variables.

We can use the example shown below to do that.

Here,

Each movie is given an index number that is used to retrieve or modify its value. Observe the following code-

Output:

Once upon a time in China Eastern Condors

As you can see from the above examples, working with arrays in PHP when dealing with multiple values of the same nature is very easy and flexible.

Alternatively, the above array variables can also be created using the following code.

 "Shaolin Monk",
               1 => "Drunken Master",
               2 => "American Ninja",
               3 => "Once upon a time in China",
               4 =>"Replacement Killers" );
echo $movie[4];
?>

Output:

Replacement Killers

PHP Associative Array

Associative array differ from numeric array in the sense that associative arrays use descriptive names for id keys.

Below is the syntax for creating associative array in php.

 value);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “['key_name']” is the access index number of the element
  • “value” is the value assigned to the array element.

  Let’s suppose that we have a group of persons, and we want to assign the gender of each person against their names.

We can use an associative array to do that.The code below helps us to do that.

 "Female", "John" => "Male", "Mirriam" => "Female");
print_r($persons); 
echo ""; 
echo "Mary is a " . $persons["Mary"];
?>

 HERE,

Output:

Array ( [Mary] => Female [John] => Male [Mirriam] => Female ) Mary is a Female

Associative array are also very useful when retrieving data from the database.

The field names are used as id keys.

PHP Multi-dimensional arrays

These are arrays that contain other nested arrays.

The advantage of multidimensional arrays is that they allow us to group related data together.

Let’s now look at a practical example that implements a php multidimensional array.

The table below shows a list of movies by category.

Movie title Category
Pink Panther Comedy
John English Comedy
Die Hard Action
Expendables Action
The Lord of the rings Epic
Romeo and Juliet Romance
See no evil hear no evil Comedy

The above information can be represented as a multidimensional array. The code below shows the implementation.

 array("Pink Panther", "John English", "See no evil hear no evil"),
"action" => array("Die Hard", "Expendables"),
"epic" => array("The Lord of the rings"),
"Romance" => array("Romeo and Juliet")
);
print_r($movies);
?>

  HERE,

Output:

Array ( [comedy] => Array ( [0] => Pink Panther [1] => John English [2] => See no evil hear no evil ) [action] => Array ( [0] => Die Hard [1] => Expendables ) [epic] => Array ( [0] => The Lord of the rings ) [Romance] => Array ( [0] => Romeo and Juliet ) )

Another way to define the same array is as follows

 array(

                                0 => "Pink Panther",

                                1 => "john English",

                                2 => "See no evil hear no evil"

                                ),

                "action" => array (

                                0 => "Die Hard",

                                1 => "Expendables"

                                ),

                "epic" => array (

                                0 => "The Lord of the rings"

                                ),

                "Romance" => array

                                (

                                0 => "Romeo and Juliet"

                                )

);
echo $film["comedy"][0];
?>

Output:

Pink Panther

  Note: the movies numeric array has been nested inside the categories associative array

PHP Arrays: Operators

Operator Name Description How to do it Output
x + y Union Combines elements from both arrays
 1);

$y = array('value' => 10);

$z = $x + $y;
?>
Array([id] => 1 [value] => 10)
X == y Equal Compares two arrays if they are equal and returns true if yes.
 1);

$y = array("id" => "1");

if($x == $y)
{
echo "true";
}
else
{
echo "false";

}
?>
True or 1
X === y Identical Compares both the values and data types
 1);

$y = array("id" => "1");

if($x === $y)
{
echo "true";
}
else
{
echo "false";
}
?>
False or 0
X != y, x y Not equal  
 1);

$y = array("id" => "1");

if($x != $y)
{
echo "true";
}
else
{
echo "false";
}
?>
False or 0
X !== y Non identical  
 1);

$y = array("id" => "1");

if($x !== $y)
{
echo "true";
}
else
{
echo "false";
}
?>
True or 1

PHP Array Functions

Count function

The count function is used to count the number of elements that an php array contains. The code below shows the implementation.

Output:

3

is_array function

The is_array function is used to determine if a variable is an array or not. Let’s now look at an example that implements the is_array functions.

Output:

1

Sort

This function is used to sort arrays by the values.

If the values are alphanumeric, it sorts them in alphabetical order.

If the values are numeric, it sorts them in ascending order.

It removes the existing access keys and add new numeric keys.

The output of this function is a numeric array

 "Female", "John" => "Male", "Mirriam" => "Female");

sort($persons);

print_r($persons);
?>

Output:

Array ( [0] => Female [1] => Female [2] => Male )

ksort

This function is used to sort the array using the key. The following example illustrates its usage.

 "Female", "John" => "Male", "Mirriam" => "Female");

ksort($persons);

print_r($persons);
?>

Output:

Array ( [John] => Male [Mary] => Female [Mirriam] => Female )

asort

This function is used to sort the array using the values. The following example illustrates its usage.

 "Female", "John" => "Male", "Mirriam" => "Female");

asort($persons);

print_r($persons);

?>

Output:

Array ( [Mary] => Female [Mirriam] => Female [John] => Male )

Why use arrays?

  • Contents of Arrays can be stretched,
  • Arrays easily help group related information such as server login details together
  • Arrays help write cleaner code.