Accessing objects in php

How to extract and access JSON data in PHP

JavaScript Object Notation(JSON) is a lightweight human-readable text format for storing and transporting data consisting of name-value pairs and arrays.

It is easy to generate and parse in many programming languages. It is the most popular and lightweight data-interchange format for web applications and the de-facto format for the data exchange in RESTful web services requests and responses.

In this post, we will cover how to decode a JSON object and access its data in PHP.

Below is an example of a simple JSON object:

How to receive JSON data in PHP

1. From a POST or GET request

To receive JSON data as a POST request, we use the “php://input” along with the function file_get_contents() as below:

For instance, the JSON data is sent below as a POST request:

'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $payload); curl_exec($curl); curl_close($curl); 

To receive the above request data in the register.php file, just add file_get_contents(«php://input») and assign it to a variable for processing eg:

2. Reading a JSON file

A JSON file contains a JSON object and has a file extension of .json. You can as well open the file in PHP and access its data.

Similar to POST or GET request, we use file_get_contents() but instead of having “php://input”, we use the file path.

For example, if we have a JSON file with path «https://www.example.com/mydata.json«, we can access its data as below:

If the json file and the PHP file accessing it are in the same website, we can use relative path instead of the full file URL.

Extracting/Decoding JSON data in PHP

We use the built-in function json_decode() to convert the JSON string to the appropriate data type such as an object or an array.

1. Accessing JSON data as a PHP object

By default the json_decode() function returns an object.

Example
The example below decodes a JSON object into a PHP object:

'; $data = json_decode($json); var_dump($data); 

The above example outputs below:

object(stdClass)#1 (4) < ["firstName"]=>string(4) «John» [«lastName»]=> string(3) «Doe» [«email»]=> string(17) «johndoe@gmail.com» [«phone»]=> string(12) «111-111-1111» >

To access the PHP object data, you use the object operator (->) after the object name, followed by the key of the key-value pair. This is the same as the name in the name-value pair in JSON object eg $data->firstName .

'; $data = json_decode($json); echo "My name is".$data->firstName." ".$data->lastName; //Output: My name is John Doe 

2. Accessing JSON data as an array

You can as well convert the JSON object to a PHP associative array by passing a second(optional) parameter in the json_decode() function with the boolean value «true» as below. The value is set to false by default if you don’t pass it.

Читайте также:  Python ответ на ping

The example below decodes JSON object into a PHP associative array:

'; $data = json_decode($json, true); var_dump($data); 

The above example outputs below:

array(4) < ["firstName"]=>string(4) «John» [«lastName»]=> string(3) «Doe» [«email»]=> string(17) «johndoe@gmail.com» [«phone»]=> string(12) «111-111-1111» >

You access the data as in any other PHP associative array as in the example below:

'; $data = json_decode($json, true); echo "My name is ".$data["firstName"]." ".$data["lastName"]; //Output: My name is John Doe 

3. Accessing data in a nested JSON object

A JSON object may comprise of json objects and arrays as the values in its name-value pairs such as in the example below:

In the above example, the «address» has an object as its value while «siblings» has an array value comprising of objects.

The easiest way of accessing all the data is decoding the object as an associative array.

, "siblings": [ < "name": "Joseph Doe" >, < "name": "Mary Doe" >] >'; $data = json_decode($json, true); //Displaying all the data echo "First Name: ".$data["firstName"]."
"; //Output -> First Name: John echo "First Name: ".$data["lastName"]."
"; //Output -> Last Name: Doe echo "Email Address: ".$data["email"]."
"; //Output -> Email Address: johndoe@gmail.com echo "Postal Address: ".$data["address"]["postalAddress"]."
"; //Output -> Postal Address: 12345 echo "Postal Code: ".$data["address"]["postalCode"]."
"; //Output -> Postal Code: 5432 echo "City: ".$data["address"]["city"]."
"; //Output -> City: Nairobi echo "Sibling 1: ".$data["siblings"][0]["name"]."
"; //Output -> Sibling 1: Joseph Doe echo "Sibling 2: ".$data["siblings"][1]["name"]."
"; //Output -> Sibling 2: Mary Doe

Looping through an object of objects with foreach()

You may have a large JSON object made of an array of objects, like in the example below:

To access the values of a country in the example above, you just have to know its object position in the array. For example, china is in the third position. But when accessing the array items, we start counting from 0, hence the index of China in the array is 2.

We access the China array object as below:

"; //Output -> Country: China echo "Code: ".$data["countries"][2]["code"]."
"; //Output -> Code: CN echo "City: ".$data["countries"][2]["city"]."
"; //Output -> City: Beijing

If you want to access all the array data then it can be tiresome and time-consuming to write the code for accessing each at a time especially when the object is large. For such an instance, you can use the foreach() function to loop through all the objects as below:

, < "name": "India", "code": "IN", "city": "New Delhi" >, < "name": "China", "code": "CN", "city": "Beijing" >, < "name": "Germany", "code": "DE", "city": "Berlin" >, < "name": "Kenya", "code": "KE", "city": "Nairobi" >] >'; $countries = json_decode($json)->countries; foreach($countries as $country)< echo "Country: ".$country->name."
"; echo "Code: ".$country->code."
"; echo "City: ".$country->city."
"; >

Conclusion

In this post, we have covered everything you need to know in extracting and accessing a JSON object data using PHP.

Читайте также:  Set window size in html

If you want to get notified via email when we add more incredible content to our blog, kindly subscribe to our email newsletter.

Источник

PHP Objects

Summary: in this tutorial, you will learn about PHP objects, how to define a class, and how to create an object from a class.

What is an Object

If you look at the world around you, you’ll find many examples of tangible objects: lamps, phones, computers, and cars. Also, you can find intangible objects such as bank accounts and transactions.

All of these objects share the two common key characteristics:

For example, a bank account has the state that consists of:

A bank account also has the following behaviors:

PHP objects are conceptually similar to real-world objects because they consist of state and behavior.

An object holds its state in variables that are often referred to as properties. An object also exposes its behavior via functions which are known as methods.

What is a class?

In the real world, you can find many same kinds of objects. For example, a bank has many bank accounts. All of them have account numbers and balances.

These bank accounts are created from the same blueprint. In object-oriented terms, we say that an individual bank account is an instance of a Bank Account class.

By definition, a class is the blueprint of objects. For example, from the Bank Account class, you can create many bank account objects.

The following illustrates the relationship between the BankAccount class and its objects. From the BankAccount class you can create many BankAccount objects. And each object has its own account number and balance.

Define a class

To define a class, you specify the class keyword followed by a name like this:

 class ClassName < //. >Code language: HTML, XML (xml)

For example, the following defines a new class called BankAccount :

 class BankAccount  Code language: HTML, XML (xml)

By convention, you should follow these rules when defining a class:

  • A class name should be in the upper camel case where each word is capitalized. For example, BankAccount , Customer , Transaction , and DebitNote .
  • If a class name is a noun, it should be in the singular noun.
  • Define each class in a separate PHP file.

From the BankAccount class, you can create a new bank account object by using the new keyword like this:

 class BankAccount  < >$account = new BankAccount();Code language: HTML, XML (xml)

In this syntax, the $account is a variable that references the object created by the BankAccount class. The parentheses that follow the BankAccount class name are optional. Therefore, you can create a new BankAccount object like this:

$account = new BankAccount;Code language: PHP (php)

The process of creating a new object is also called instantiation. In other words, you instantiate an object from a class. Or you create a new object from a class.

The BankAccount class is empty because it doesn’t have any state and behavior.

Add properties to a class

To add properties to the BankAccount class, you place variables inside it. For example:

 class BankAccount < public $accountNumber; public $balance; >Code language: HTML, XML (xml)

The BankAccount class has two properties $accountNumber and $balance . In front of each property, you see the public keyword.

The public keyword determines the visibility of a property. In this case, you can access the property from the outside of the class.

To access a property, you use the object operator ( -> ) like this:

 $object->property;Code language: HTML, XML (xml)

The following example shows how to set the values of the accountNumber and balance properties:

 class BankAccount < public $accountNumber; public $balance; > $account = new BankAccount(); $account->accountNumber = 1; $account->balance = 100;Code language: HTML, XML (xml)

Besides the public keyword, PHP also has private and protected keywords which you’ll learn in the access modifiers tutorial.

Add methods to a class

The following shows the syntax for defining a method in a class:

 class ClassName < public function methodName(parameter_list) < // implementation > >Code language: HTML, XML (xml)

Like a property, a method also has one of the three visibility modifiers: public , private , and protected . If you define a method without any visibility modifier, it defaults to public .

The following example defines the deposit() method for the BankAccount class:

 class BankAccount < public $accountNumber; public $balance; public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > > >Code language: HTML, XML (xml)

The deposit() method accepts an argument $amount . It checks if the $amount is greater than zero before adding it to the balance.

To call a method, you also use the object operator ( -> ) as follows:

$object->method(arguments)Code language: PHP (php)

The new syntax in the deposit() method is the $this variable. The $this variable is the current object of the BankAccount class.

For example, when you create a new object $account and call the deposit() method, the $this inside the method is the $account object:

$account = new BankAccount(); $account->accountNumber = 1; $account->balance = 100; $account->deposit(100);Code language: PHP (php)

Similarly, you can add the withdraw() method to the BankAccount class as follows:

 class BankAccount < public $accountNumber; public $balance; public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > > public function withdraw($amount) < if ($amount $this->balance) < $this->balance -= $amount; return true; > return false; > >Code language: HTML, XML (xml)

The withdraw() method checks the current balance.

If the balance is less than the withdrawal amount, the withdraw() method returns false .

Later, you’ll learn how to throw an exception instead. Otherwise, it deducts the withdrawal amount from the balance and returns true .

Summary

  • Objects have states and behaviors.
  • A class is a blueprint for creating objects.
  • Properties represent the object’s state, and methods represent the object’s behavior. Properties and methods have visibility.
  • Use the new keyword to create an object from a class.
  • The $this variable references the current object of the class.

Источник

Оцените статью