PHP / PHP APIs and Web Services

Handling JSON and XML in PHP

This tutorial will teach you how to handle JSON and XML data in PHP. You'll learn how to encode and decode data in these formats and work with them in APIs.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers creating and consuming REST APIs and working with web services in PHP.

Handling JSON and XML in PHP

1. Introduction

In this tutorial, we're going to explore how to handle JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) data in PHP. These are popular data formats often used for transmitting data in web applications, especially in APIs.

By the end of this tutorial, you will learn:
- How to encode and decode JSON in PHP
- How to parse and generate XML in PHP

Prerequisites: Basic understanding of PHP and data formats like JSON and XML

2. Step-by-Step Guide

JSON in PHP

PHP provides built-in functions to encode and decode JSON data.

  • json_encode(): This function is used to encode a value to JSON format
  • json_decode(): This function is used to decode a JSON string

XML in PHP

PHP's SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.

  • simplexml_load_string(): This function is used to interpret a string of XML into an object

3. Code Examples

JSON Example

// create an array
$data = array('name' => 'John', 'age' => 30, 'city' => 'New York');

// encode the array into JSON format
$json_data = json_encode($data);

echo $json_data; // output: {"name":"John","age":30,"city":"New York"}

// decode the JSON data
$decoded_data = json_decode($json_data);

print_r($decoded_data); // output: stdClass Object ( [name] => John [age] => 30 [city] => New York )

XML Example

// create a XML string
$xml_string = <<<XML
<?xml version="1.0"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>
XML;

// convert the XML string into an object
$xml = simplexml_load_string($xml_string);

echo $xml->to; // output: Tove

4. Summary

In this tutorial, we've learned how to handle JSON and XML data in PHP using built-in PHP functions like json_encode(), json_decode() and simplexml_load_string().

To continue learning, you could explore more about handling errors while encoding/decoding JSON and parsing/generating XML. You could also learn more about other PHP extensions for handling XML, like DOM and XMLReader.

5. Practice Exercises

Exercise 1:

Create an array of your favorite movies with their director and year of release. Encode this array into JSON and then decode it.

Exercise 2:

Create an XML string for a book catalog. Each book should have a title, author, and publication year. Convert this XML string into an object and display the title of the first book.

Solutions:

Exercise 1:

$movies = array(
    array('title' => 'Inception', 'director' => 'Christopher Nolan', 'year' => 2010),
    array('title' => 'The Dark Knight', 'director' => 'Christopher Nolan', 'year' => 2008),
    // add more movies
);

$json_movies = json_encode($movies);

print_r(json_decode($json_movies));

Exercise 2:

$xml_string = <<<XML
<?xml version="1.0"?>
<catalog>
   <book>
      <title>Harry Potter</title>
      <author>J.K. Rowling</author>
      <year>1997</year>
   </book>
   <!-- add more books -->
</catalog>
XML;

$xml = simplexml_load_string($xml_string);

echo $xml->book[0]->title; // output: Harry Potter

Happy Coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help