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.

<?php
error_reporting(0);
$var = '[{"A":"MyName","B":"www.example.com","C":"www.example.com/2/"},{"A":"MyName","B":"www.example.ca/","C":"www.example.ca/2/"}]';

// 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));

//print_r($myarray);

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

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


Browser Output

0-www.example.com

1-www.example.ca/