Free cookie consent management tool by TermsFeed Generator PHP xml and json | Amir Kamizi
AMIR KAMIZI
Home Blog Courses Books Newsletter Store Membership Buy me a coffee
PHP xml and json

PHP xml and json

Last Updated on Mar 21, 2023

Intro

Xml and json are the most common formats that are used in APIs. knowing how to work with them is essential for any webdeveloper.

Json is human readable and very light in terms of size and it's not verbose. a lot of modern APIs are using Json to pass data.

a Json file looks something like this:

{
  "accounts": {
    "twitter": "Pratham",
    "feedhive": "Simon",
    "php": "Amir"
  }
}

xml is more verbose. at first sight you might say why should I even bother working with xml. but xml has some advantages over json like validating the structure and format and data is much easier in xml.

a xml file looks something like this

<?xml version="1.0" encoding="UTF-8" ?>
<accounts>
    <account type="twitter">Pratham</account>
    <account type="feedhive">Simon</account>
    <account type="php">Amir</account>
</accounts>

Reading JSON

In php reading json is very easy because you can use the json_decode function and read it like an array. the first argument is the json string and set the second argument "true" to convert your json to an associative array.

$array = json_decode($json, true);
print_r($array);
// Array ( [accounts] => Array ( [twitter] => Pratham [feedhive] => Simon [php] => Amir ) )

Writing JSON

You can easily convert your array to json with json_encode function

$array = [
    'accounts' => [
        'twitter'  => 'Pratham',
        'feedhive' => 'Simon',
        'php'      => 'Amir',
    ]
];

$json = json_encode($array, true);
echo $json;
// {"accounts":{"twitter":"Pratham","feedhive":"Simon","php":"Amir"}}

Reading XML

There are 2 functions that can help us read xmls in php:

  1. DOMDocument
  2. SimpleXMLElement

1. DOMDocument

after loading the xml it returns an object. with this object you can get all the tags with specific name. then loop through them and get the text inside the tag with nodeValue and get the attribute of the tag with getAttribute

$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<accounts>
    <account type="twitter">Pratham</account>
    <account type="feedhive">Simon</account>
    <account type="php">Amir</account>
</accounts>';

$dom = new DOMDocument();
$dom->loadXML($xml);
echo 'accounts => ';
foreach ($dom->getElementsByTagName('account') as $account) {
    $name = $account->nodeValue;
    $type = $account->getAttribute('type');
    echo "$type : $name. ";
}
// accounts => twitter : Pratham. feedhive : Simon. php : Amir.

2. SimpleXMLElement

this returns an xml element that behaves like an object but inside the object the attributes and values are like arrays. as the name suggests this is very simple to use but rarely you might face some strange behaviours.

$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<accounts>
    <account type="twitter">Pratham</account>
    <account type="feedhive">Simon</account>
    <account type="php">Amir</account>
</accounts>';

$accounts = new SimpleXMLElement($xml);
echo 'accounts => ';
foreach ($accounts as $account) {
    $name = $account;
    $type = $account['type'];
    echo "$type : $name. ";
}

Writing XML

one way is to write as string but a better and easier way is to use SimpleXMLElement to write your xml. here's how:

$accounts = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?><accounts />');
$accounts->addChild('account','Pratham')->addAttribute('type','twitter');
$accounts->addChild('account','Simon')->addAttribute('type','feedhive');
$accounts->addChild('account','Amir')->addAttribute('type','php');
$finalXml = $accounts->asXML();

echo $finalXml;
/*
<?xml version="1.0" encoding="UTF-8"?>
<accounts>
    <account type="twitter">Pratham</account>
    <account type="feedhive">Simon</account>
    <account type="php">Amir</account>
</accounts>
*/

first argument of addChild is tag name and the second argument is the text inside the tag.

first argument of addAttribute is the attribute name and the second argument is the attribute value.

https://youtu.be/bLp-xAtzE_k

Conclusion

Now you know about JSON and XML in PHP.

I recommend you to open a PHP files and try to write JSON files and the read them. then do the same with XML.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • XML and JSON in PHP
  • read JSON
  • write JSON
  • read XML
  • write XML

Category: programming

Tags: #php

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Ultimate guide to RESTFul API Versioning in PHP Laravel: 2 solutions
Feb 15, 2023 programming

Ultimate guide to RESTFul API Versioning in PHP Laravel: 2 solutions

API versioning is what you need if you want to change the behavior of your API or the structure and format of requests and responses. ...

17 Min Read Read More
PHP CSV Files
Mar 21, 2023 programming

PHP CSV Files

Today we are going to talk about working with a csv files in PHP. Comma Separated Values (csv) is a common way to store the data in a file and it's important to know how to work with them. ...

5 Min Read Read More
PHP simple REST API
Feb 15, 2023 programming

PHP simple REST API

Today we are going to create a simple REST API in PHP. we are going to do it with pure PHP and with no frameworks. you can create a RESTful API in 70 lines of code. ...

25 Min Read Read More

Recommended Courses

Introduction to Machine Learning in PHP

Introduction to Machine Learning in PHP

Learn to Build Different Machine Learning Models Easily ...

PHP Tutorial Beginner to Advanced

PHP Tutorial Beginner to Advanced

Learn everything you need to start a successful career as a PHP developer ...