Category: xml

difference between JSON and XML
difference between JSON and XML

JSON Tutorial: JSON and XML


JSON and XML:  Hi readers, in this JSON Tutorial we have explained the JSON and XML. As both, JSON and XML are mainly used to exchange data but we find some of the differences between them which make JSON more powerful and advantageous over XML. Here in this tutorial first we list out the differences between JSON and XML and further we explain some of the similarities as well. And then the Simple example of JSON File and XML File containing same data makes you more clear between JSON and XML.

Difference Between JSON and XML:


  • 1)  JSON is developed by Douglas Crockford and XML is developed by W3C(World Wide Web Consortium)
    2)  JSON Stands for JavaScript Object Notation whereas XML stands for eXtensible Markup Language.
    3)   JSON is extended from JavaScript whereas XML is extended from SGML(Standard Generalized Markup Language)
    4)   JSON is data oriented whereas XML is document oriented.
    5)   JSON is faster and easier than XML.
    6)   JSON store the data in KEY/VALUE format whereas XML store data using tags i.e start and end tag both are compulsory.
    7)   JSON Syntax is lighter than XML or we can say JSON is light-weighted as it has serialized format whereas XML is not so light-weighted.
    8)   JSON is the text-based format and it is standard of interchanging data i.e. Humanly readable whereas XML is Markup Language having format which contains some set of rules like every start tag must have an end tag, etc. i.e both human and machine readable.
    9)   JSON supports only text and numeric datatype whereas XML supports all type of datatype including text, numeric, image,           chart, graphs etc.
    10)  JSON also support array and native objects whereas XML has no direct support for array and objects. Like, through a mixed use of attributes and elements XML can support native objects.
    11)  JSON does not support Comments whereas XML supports Comments.
    12)  JSON also does not have any support for Namespaces whereas XML supports Namespaces.

 Similarities between JSON and XML:


  •     1)  Both JSON and XML are used to exchange data over servers.
        2)  Both are Language-Independent, self-describing and self-understandable.
       3)  Both are open and human-readable.
             4)  Both supports interoperability feature.

Simple Example of the File format of JSON and XML:


Here in this simple example we have stored some information of student using  .json and .xml file.

Both files contain the same data but in a different format. So that one can easily differentiate between JSON & XML file Format.

info.json


{ "studentId": "SJ011MS",
 "student": {
 "name": "Deepak Singh",
 "gender": "Male",
 "age": "27",
 "address": {
 "city": "varanasi",
 "state": "Uttar Pradesh",
 "pincode": "221001"
 }
 },
 "course": "B.S.c",
 "section": "B"
 
}

info.XML


<?xml version="1.0"?>
<student>

<studentId>SJ011MS</studentId>
<name>Deepak Singh</name>
<gender>Male</gender>
<age>27</age>

<address>
<city>varanasi</city>
<state>Uttar Pradesh</state>
<pincode>221001</pincode>
</address>

<course>B.S.c</course>
<section>B</section>

</student>


                                                                                                            

read or display data from XML file


Read or display data from the XML fileHi readers, as we have already explained how we can insert data into XML file in our previous post today we come up with the topic of read or display data from XML file. Here in this tutorial, we begin with a brief introduction of XML then proceed to the simple example to read/select/display data into XML using PHP code with an explanation of full source code which is in a readable format and then the snapshot view which makes you more clear. So no need to worry even for beginners!.Here we start topic on read or display data from the XML file

Brief Introduction On XML

XML stands for eXtensible Markup Language which is a Markup language similar to HTML but not exactly like that.

HTML is mainly designed to give layout structure of any web page which mainly focuses on how data looks but XML is designed mainly to transport data and store it independent of any hardware and software tool which focuses on what data is.

There is two main differences between XML and HTML:

1.)  In XML there is no specific tags defined which can be used but we can create our own tags as per need whereas in HTML there is a specific      tags defined already which is used to make the layout of website like <p>,<h>,<img> etc. and other than those defined tags we can’t create our    own tags.

2.)  XML is an strict markup language that means every opened tags must have a closed tags whereas in HTML there is no such restrictions.

Simple Example to read or  display data from the XML file: 

Here is the Simple example to select or display data from XML file via a PHP script.

Step 1: First Create an XML file or use a saved XML file.

Here we have used the simple saved XML file named studentxml.xml

studentxml.xml
<?xml version="1.0"?>
<student>
<id>1</id>
<name>Anvita Rai</name>
<Rollno>08</Rollno>
<schoolname>Guru Nanak english School</schoolname>
<age>21</age>

</student>

Step 2: Create a PHP file  ‘readxml.php’ to display or read data from XML file.

Here in this step, we can use either of the two methods described below i.e by Specific id or directly by attribute name. One thing is common in both the files that here we use the SimpleXML parser and simplexml_load_file() method to load the .xml files which are to be read.

(1)   Create a PHP file named ‘readxml.php’ to select data by specific id in XML. Load the file then provide the path using xpath and store it in a variable.If it is not empty the print all the records one by one else show ” no records are there” using echo statement

Note:     DOM (Document Object Model) is an object so we use the access operator(->) to access different attribute.

readxml.php
<?php
/* PHP Script to read an xml file and display data by particular "id"*/

/* simplexml parser is used to load the xml file if exists
 otherwise show error message and exit using die() function 
 */

$xml=simplexml_load_file("studentxml.xml") or die("Error: cannot create Object");

$student=$xml->xpath('//student[id=1]');

//print all the records of loaded xml file in an associative array in format of key & value pair
print_r($xml);

//print all the records one by one using echo and print statement

if(!empty($student)){
 $item=$student[0];
 echo "<br><br>All the records one by one:<br>id:=";
 print $item->id;
 echo "<br>Name:= ";
 print $item->name;
 echo "<br>Rollno:= ";
 print $item->Rollno;
 echo "<br>School Name:=";
 print $item->schoolname;
 echo "<br>Age:=";
 print $item->age;
 echo "<br>";
}
else
{ echo "No records";
}

?>

 OR

(2.)  Create a PHP file named read1.xml and copy the below code and then save it.

Here first Load the .xml file then use the print_r() method to print all the records in an associative array of key-value pair to get the attribute name i.e. Key so that it is further used to display data by using access operator(->).

 read1.xml
<?php

/*--- php code begins---*/
/* ---PHP Script to read an xml file and display data by "attribute" 

   --- simplexml parser is used to load the xml file if exists
       otherwise show error message and exit using die() function 
 ---*/

$xml=simplexml_load_file("studentxml.xml") or die("Error: cannot create Object");

//print all the records of loaded xml file in an associative array in format of key & value pair
print_r($xml);

//print records directly by attribute "name" using echo statement

echo "<br><br>$xml->name";

/*--php code ends--*/
?>

Screenshot View of readxml.xml file:

Read or display data from the XML file
Read or display data from the XML file

Screenshot View read1.xml file:

Read or display data from the XML file
Read or display data from the XML file

Download source code

 display-data-from-XML.zip

 

I hope you would like this tutorial to read or display data from XML file using PHP Script!

Insert data into XML file

 


insert data into XML fileHi readers today we come up with the new concept of PHP with XML(eXtensible Markup Language). Here in this tutorial, we begin with a brief introduction of XML then proceed to the simple example to insert data into XML using PHP code with an explanation of full source code which is in a readable format and then the snapshot view which makes you more clear. So no need to worry even for beginners!.Here we starts topic on insert data into XML file.

Brief Introduction On XML

XML stands for eXtensible Markup Language which is a Markup language similar to HTML but not exactly like that.

HTML is mainly designed to give layout structure of any web page which mainly focuses on how data looks but XML is designed mainly to transport data and store it independent of any hardware and software tool which focuses on what data is.

There is two main differences between XML and HTML:

1.)  In XML there is no specific tags defined which can be used but we can create our own tags as we like whereas in HTML there is a specific tags      defined already which is used to make the layout of website like <p>,<h>,<img> etc. and other than those defined tags we can’t create our own tags.

2.)  XML is an strict markup language that means every opened tags must have a closed tags whereas in HTML there is no such restrictions.

Simple Example to insert data into XML file: 

Here is the Simple example to insert data into XML file via PHP script.

Step 1: First Create a XML file.

Here is the simple XML file named studentxml.xml with only one element <student>..</student>

studentxml.xml
<?xml version="1.0"?>
<student>


</student>

Step 1: Create a PHP file  ‘student.php’ to insert data into XML file.

Here in this step we create a PHP file named ‘student.php’ to insert records using XML. To insert records here we use a tree like structure.

First of all we create the new DOM element using new keyword and then store all the data in the variable. If the created .xml file has some contents then starts inserting the element after loading the .xml file and capture the first child(root node) in a $root variable.

The element is created under root element using createElement() method and then append to the root element using appendChild() method and insert the text in between the created element using createTextNode() method.This process repeats for each element you want to insert.

Note:

DOM (Document Object Model) is an object so we use the access operator(->) to access different methods like loadXML()createElement(), createTextNode(), appendChild() method.

student.php
<?php

 //create a new DOM document
 $xmldoc=new DomDocument();
 $xmldoc->formatOutput=true;

//Assign variables to store values

 $id="1";
 $name="Anvita Rai";
 $Rollno="08";
 $schoolname="Guru Nanak english School";
 $age="21";
 
 if($xml=file_get_contents('studentxml.xml')){
 $xmldoc->loadXML($xml);
 $root=$xmldoc->firstChild;
 

  //create a new element
 //first element 'id' is created
 $newElement=$xmldoc->createElement('id');


 //append the created element in first child 'root'
 $root->appendChild($newElement);


 //text is inserted in between the node using createTextNode()
 $idText=$xmldoc->createTextNode($id);


 //append the text in the element
 $newElement->appendChild($idText);
 
 
 //second column of 'name'

 $nameElement=$xmldoc->createElement('name');
 $root->appendChild($nameElement);
 $nameText=$xmldoc->createTextNode($name);
 $nameElement->appendChild($nameText);
 
 //third column 'Rollno'

 $RollnoElement=$xmldoc->createElement('Rollno');
 $root->appendChild($RollnoElement);
 $RollText=$xmldoc->createTextNode($Rollno);
 $RollnoElement->appendChild($RollText);
 
//fourth column 'Schoolname'

 $schoolnameElement=$xmldoc->createElement('schoolname');
 $root->appendChild($schoolnameElement);
 $schoolText=$xmldoc->createTextNode($schoolname);
 $schoolnameElement->appendChild($schoolText);
 
 //fifth column 'age'

 $ageElement=$xmldoc->createElement('age');
 $root->appendChild($ageElement);
 $ageText=$xmldoc->createTextNode($age);
 $ageElement->appendChild($ageText);
 
 
 //save the xml file using save('filename.xml') method
 
 $xmldoc->save('studentxml.xml'); 
 }

?>


Screenshot View:

After running the student.php file on browser. The following dialog box appears to reload the file. Press ‘yes to reload a file after inserting data into XML file through PHP Script.

insert data into XML file
insert data into XML file
The screenshot view of student.xml file after clicking Yes button

 

 

insert data into XML file
insert data into XML file

I hope you would like this tutorial to insert data into XML file using PHP Script!

 

Next Topic to read data from XML

Web Service

Web Service Using PHP, MySQL, XML, and JSON

Web service in PHP Consists of protocol like XML, JSON,etc..that  interact between other web applications to get output in the form of XML  and JSON to the purpose of exchange data.

You can exchange data between two web applications built on different platform languages.To exchange data we need output in the form of XML and JSON. Which are protocols that are used to exchange information between web applications?

 XML

XML stands for Extensible Markup Language is an important protocol of web services in PHP. It can be used to store and exchange data while communicating between web applications.XML was designed to be both human- and machine-readable.

JSON

JSON  (JavaScript Object Notation) is a lightweight data-interchange format.which can also store and exchange data.Output comes in the form of text and it is also human-readable and completely language independent.

Create a Basic Web Service Using PHP

First of all, we have to create a web service file in which we have to write a code in PHP & MySQL to get the response in the form of JSON and XML.You have to create  a file name with webservice.php on server and copy the below code

The PHP / MySQL Web service Code

/* require the user as the parameter */
if(isset($_GET['userid']) && intval($_GET['userid'])) {

	/* here you can configure format of output,number of records you want to fetch */
	$number_of_posts = isset($_GET['number']) ? intval($_GET['number']) : 20; //20 is the default
	$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
	$user_id = intval($_GET['userid']); //no default

	/* connect to the mysql database with your own database setting */
	$link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');
	mysql_select_db('db_name',$link) or die('Cannot select the DB');

	/* grab the posts from the database you can customize your query on the basis of table */
	$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
	$result = mysql_query($query,$link) or die('Errant query:  '.$query);

	/* create one master array of the records */
	$posts = array();
	if(mysql_num_rows($result)) {
		while($post = mysql_fetch_assoc($result)) {
			$posts[] = array('post'=>$post);
		}
	}

	/* output in JSON format */
	if($format == 'json') {
		header('Content-type: application/json');
		echo json_encode(array('posts'=>$posts));
	}
	else {
/*  XML FORMAT Output*/

		header('Content-type: text/xml');
		echo '<posts>';
		foreach($posts as $index => $post) {
			if(is_array($post)) {
				foreach($post as $key => $value) {
					echo '<',$key,'>';
					if(is_array($value)) {
						foreach($value as $tag => $val) {
							echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
						}
					}
					echo '</',$key,'>';
				}
			}
		}
		echo '</posts>';
	}

	/* disconnect from the db */
	@mysql_close($link);
}


In the above code, First of all, we have configured the input value to interact with the web application.Then we have to write a code to connect with the database after executing the query, we will get the result and that output result we have converted in the format like  JSON and XML in the form of an array.

Take the following example URL for web service :

http://techieflair.com/webservice.php?userid=1&number=10


After Executing above URL you will get result in XML format

 XML Output

<posts>
<post>
<post_title>Armstrong In C#</post_title>
<guid>http://techieflair.com/?p=1243</guid>
</post>

<post>
<post_title>Web Service Using PHP, MySQL, XML, and JSON</post_title>
<guid>http://techieflair.com/?p=1235</guid>
</post>

<post>
<post_title>Sort Array Item using Selection Sort In C#</post_title>
<guid>http://techieflair.com/?p=1232</guid>
</post>

<post>
<post_title>How to check a string is Polindrome or not in C#</post_title>
<guid>http://techieflair.com/?p=1224</guid>
</post>

<post>
<post_title>
Simple Example using Jquery DataTable in ASP.NET MVC
</post_title>
<guid>http://techieflair.com/?p=1216</guid>
</post>

<post>
<post_title>What is Visualforce?</post_title>
<guid>http://techieflair.com/?p=1193</guid>
</post>
<post>
<post_title>
DIFFERENCE BETWEEN ABSOLUTE,FIXED ,STATIC & RELATIVE:
</post_title>
<guid>http://techieflair.com/?p=1192</guid>
</post>
<post>
<post_title>MS word shortcut keys</post_title>
<guid>http://techieflair.com/?p=1183</guid>
</post>
<post>
<post_title>clear dns cache</post_title>
<guid>http://techieflair.com/?p=1174</guid>
</post>
<post>
<post_title>Machine Learning Techniques</post_title>
<guid>http://techieflair.com/?p=1160</guid>
</post>
</posts>

 

 

JSON Output

Take this next  URL for Web Sevice  to get a result in JSON Format:

http://techieflair.com/webservice.php?userid=1&number=10&format=json
{"posts":[{"post":{"post_title":"Armstrong In C#","guid":"http:\/\/techieflair.com\/?p=1243"}},{"post":{"post_title":"Sort Array Item using Selection Sort In C#","guid":"http:\/\/techieflair.com\/?p=1232"}},{"post":{"post_title":"How to check a string is Polindrome or not in C#","guid":"http:\/\/techieflair.com\/?p=1224"}},{"post":{"post_title":"Simple Example using Jquery DataTable in ASP.NET MVC","guid":"http:\/\/techieflair.com\/?p=1216"}},{"post":{"post_title":"What is Visualforce?","guid":"http:\/\/techieflair.com\/?p=1193"}},{"post":{"post_title":"DIFFERENCE BETWEEN  ABSOLUTE,FIXED ,STATIC & RELATIVE","guid":"http:\/\/techieflair.com\/?p=1192"}},{"post":{"post_title":"MS word shortcut keys","guid":"http:\/\/techieflair.com\/?p=1183"}},{"post":{"post_title":"clear dns cache","guid":"http:\/\/techieflair.com\/?p=1174"}},{"post":{"post_title":"Machine Learning Techniques","guid":"http:\/\/techieflair.com\/?p=1160"}},{"post":{"post_title":"Machine Learning","guid":"http:\/\/techieflair.com\/?p=1157"}}]}

It is very easy to create a web service in PHP. Share others to do same.Hope this article will help you.

Thank You