Assignments On Class 37: Working with XML and JSON
Assignments:
Working with XML and JSON in PHP
Assignment
1: Parsing and Manipulating XML
Objective: Learn
how to parse and manipulate XML data using the SimpleXML extension in PHP.
Task: Write a
PHP script that reads an XML file containing information about books and prints
out the book details (title, author, publisher) in a structured format.
The XML file (books.xml) has the
following structure:
xml
Copy code
<library>
<book>
<title>PHP for
Beginners</title>
<author>John
Smith</author>
<publisher>Tech
Books</publisher>
</book>
<book>
<title>Advanced PHP</title>
<author>Jane Doe</author>
<publisher>Advanced
Publishers</publisher>
</book>
</library>
Solution:
1. Load the
XML file using simplexml_load_file().
2. Iterate
through the XML data and print the book details.
php
Copy code
<?php
$xml =
simplexml_load_file('books.xml');
foreach ($xml->book as $book)
{
echo "Title: " . $book->title
. "\n";
echo "Author: " .
$book->author . "\n";
echo "Publisher: " .
$book->publisher . "\n";
echo "---------------------\n";
}
?>
Explanation:
- simplexml_load_file()
loads the XML file into a SimpleXML object.
- A foreach
loop is used to iterate through each <book> element, and its children (title, author, publisher)
are accessed using object notation.
Assignment
2: Creating XML Data Using PHP
Objective: Learn
how to create XML data using the SimpleXML extension.
Task: Write a
PHP script that generates an XML file for a book with the following details:
- Title:
"Learning PHP"
- Author:
"John Doe"
- Publisher:
"PHP Books"
Solution:
1. Create a
new SimpleXMLElement object.
2. Add child
elements to the XML.
3. Save the
XML to a file using asXML().
php
Copy code
<?php
// Create a new XML structure
$book = new
SimpleXMLElement('<book/>');
// Add child elements
$book->addChild('title',
'Learning PHP');
$book->addChild('author',
'John Doe');
$book->addChild('publisher',
'PHP Books');
// Save XML to a file
$book->asXML('new_book.xml');
echo "XML file has been
created successfully.";
?>
Explanation:
- A
new SimpleXMLElement object is created with the root element <book>.
- addChild() is
used to add the <title>, <author>,
and <publisher> elements.
- asXML() is
used to save the XML structure to a file named new_book.xml.
Assignment
3: Converting JSON to PHP Array
Objective: Learn
how to decode JSON data into a PHP array.
Task: Write a
PHP script that decodes the following JSON string into a PHP associative array
and prints the decoded values:
json
Copy code
{
"name": "John Doe",
"age": 30,
"email":
"john.doe@example.com"
}
Solution:
1. Use json_decode() to
decode the JSON string into a PHP array.
2. Access
the array values and print them.
php
Copy code
<?php
$jsonString = '{"name":
"John Doe", "age": 30, "email":
"john.doe@example.com"}';
// Decode JSON to associative
array
$data = json_decode($jsonString,
true);
// Access and print array
elements
echo "Name: " .
$data['name'] . "\n";
echo "Age: " .
$data['age'] . "\n";
echo "Email: " .
$data['email'] . "\n";
?>
Explanation:
- json_decode()
converts the JSON string into an associative array because the second
argument is set to true.
- The
array elements are accessed using standard array notation ($data['name'], $data['age'],
etc.).
Assignment
4: Encoding PHP Data to JSON
Objective: Learn
how to encode PHP arrays or objects into JSON format.
Task: Write a
PHP script that encodes the following PHP array into a JSON string:
php
Copy code
$data = [
"name" => "Alice",
"age" => 25,
"city" => "New York"
];
Print the resulting JSON string.
Solution:
1. Use json_encode() to
encode the PHP array into JSON.
2. Print the
JSON string.
php
Copy code
<?php
$data = [
"name" => "Alice",
"age" => 25,
"city" => "New York"
];
// Encode PHP array to JSON
$jsonString = json_encode($data);
// Print the resulting JSON
string
echo $jsonString;
?>
Output:
json
Copy code
{"name":"Alice","age":25,"city":"New
York"}
Explanation:
- json_encode()
converts the PHP array into a JSON string.
- The
result is a string in JSON format.
Assignment
5: Converting JSON to XML
Objective: Learn
how to convert JSON data into XML format.
Task: Write a
PHP script that converts the following JSON string into XML format and prints
it:
json
Copy code
{
"title": "PHP for
Beginners",
"author": "John Smith",
"publisher": "Tech
Publishers"
}
Solution:
1. Decode
the JSON string into a PHP array.
2. Create
XML structure using SimpleXML and populate it with the array
data.
php
Copy code
<?php
$jsonString =
'{"title": "PHP for Beginners", "author":
"John Smith", "publisher": "Tech Publishers"}';
// Decode JSON to PHP array
$data = json_decode($jsonString,
true);
// Create a new SimpleXMLElement
object
$xml = new SimpleXMLElement('<book/>');
// Add elements to the XML
array_walk_recursive($data,
function($value, $key) use ($xml) {
$xml->addChild($key, $value);
});
// Output the XML
echo $xml->asXML();
?>
Output:
xml
Copy code
<?xml
version="1.0"?>
<book>
<title>PHP for Beginners</title>
<author>John Smith</author>
<publisher>Tech
Publishers</publisher>
</book>
Explanation:
- The json_decode()
function converts the JSON string into an associative array.
- array_walk_recursive() is
used to traverse the array and add each key-value pair to the XML document
using addChild().
- asXML()
outputs the XML structure as a string.
Assignment
6: Converting XML to JSON
Objective: Learn
how to convert XML data into JSON format.
Task: Write a
PHP script that converts the following XML data into JSON format and prints it:
xml
Copy code
<book>
<title>Advanced PHP</title>
<author>Jane Doe</author>
<publisher>Tech
Press</publisher>
</book>
Solution:
1. Load and
parse the XML using simplexml_load_string().
2. Convert
the SimpleXML object to JSON using json_encode().
php
Copy code
<?php
$xmlString = <<<XML
<book>
<title>Advanced PHP</title>
<author>Jane Doe</author>
<publisher>Tech
Press</publisher>
</book>
XML;
// Load the XML string into a
SimpleXML object
$xml =
simplexml_load_string($xmlString);
// Convert SimpleXML object to
JSON
$json = json_encode($xml);
// Output the JSON string
echo $json;
?>
Output:
json
Copy code
{"title":"Advanced
PHP","author":"Jane
Doe","publisher":"Tech Press"}
Explanation:
- simplexml_load_string() is
used to parse the XML string into a SimpleXML object.
- json_encode()
converts the SimpleXML object into JSON format.
Conclusion:
These assignments cover
fundamental tasks like parsing, manipulating, and converting XML and JSON data
in PHP. By completing these exercises, students will gain a deeper
understanding of how to work with both XML and JSON, and how to use these
formats for data exchange in PHP applications.