Parse Json String Class Using PHP OOP

PHP Class To Parse Json String

This class can be used to output desired data from a Json string. Here is how it works. The Json string is fed into the constructor within the ParseJson class. Then, the public convert_to_array() function is called while passing in the $this->jsonString property.

Within the function, the Json string is decoded and array is returned. The array takes on the instance name and becomes $my_json->myarray. Thus, the loop which resides outside of the class parses the array using $my_json->myarray as $key => $val.

Class ParseJson

    public $jsonString;

    function __construct($json_string)
        $this->jsonString = $json_string;

    public function convert_to_array($json_string)
        // The second parameter in json_decode has a value of true. This is required to end up with an array.
        $this->myarray = array(json_decode($json_string, true));
        return $this->myarray;



$json_string = '[{"A":"MyName","B":"","C":""},{"A":"MyName","B":"","C":""}]';

$my_json = new ParseJson($json_string);


$i = 0;
foreach ($my_json->myarray as $key => $val) {
    $i = $i + 1;

    foreach ($val as $key2 => $val2) {
        echo $key2 . "-" . $val2['B'] . "<br/><br/>";