Site Cloner PHP Script
Bargain Hunter PHP Script
Job Hunter PHP Script
Site Login and Access Control PHP Script

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;
        $this->convert_to_array($this->jsonString);
    }

    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":"www.example.com","C":"www.example.com/2/"},{"A":"MyName","B":"www.example.ca/","C":"www.example.ca/2/"}]';

$my_json = new ParseJson($json_string);

//print_r($my_json->myarray);

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

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