Parsing a Json String With PHP

Parsing a Json String With PHP

There could come a time, when you have a Json string and you want to parse it as a regular array. There are many reasons why you could have this particular Json string.

For example, recently, I was examining the links of some high ranked websites for specific keywords and wanted to make an attempt to compete for those keywords. After analyzing their titles, content, keywords, headings and other factors, I finally came to the dreaded links. I was able to gather all of their incoming links, but, they were contained in a Json string.

So, at this point, I made a quick parser that could decode the Json string to a PHP array. Then, the array is parsed with PHP. Actually, I used a nested foreach loop to parse the value from a specific key.

The snippet below shows how easily this can be done.

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

// The second parameter in json_decode has a value of true. This is required to end up with an array.
$myarray = array(json_decode($var, true));


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

    foreach ($val as $key2 => $val2) {
        echo $key2 . "-" . $val2[B] . "\n";

Browser Output