How To Convert This jSON Extractor From OOP To Procedural ?

Folks,

I just signed-up here. :slight_smile:

I am a beginner and still on Procedural Style Php.
Do you mind converting this code to Procedural Style so I can learn from it to extract jSon off from a cURL fetched webpage ?
You see, I do not understand this oop style.

<?php 

//Code from: https://potentpages.com/web-crawler-development/tutorials/php/techniques 

//Assuming your contents are in a vairable called $contents
//Check if the JSON is valid
//Attempt to decode; return true for valid if no errors were found.
//Otherwise return false for an error
function checkIfJSONValid($t) {
    json_decode($t);
    if(json_last_error() == JSON_ERROR_NONE) {
        return true;
    }
    return false;
}
//Match all JSON and filter for valid JSON contents
$json_matches = Array();
$pattern = '/\{(?:[^{}|(?R))*\}/x';
preg_match_all($pattern, $contents, $json_matches);
$json_valid = array_filter($json_matches, 'checkIfJSONValid');
//Loop through all valid JSON strings
foreach( $json_valid as $json ) {
    //Decode JSON
    //Second parameter specifies to use an associative array for the decoded JSON data
    $data = json_decode($t, true);
    //JSON is now in an array in the $data variable
}


?> 

Ummm, this IS procedural code.

1 Like

Oops!
Do you mind converting this one so I can learn from you ? You see, I do not understand OOP atall.
I will move-onto it later.

<?php 

//Code from: https://potentpages.com/web-crawler-development/tutorials/php/techniques 

//Assuming your contents are in a variable called $contents
//New DOM Document
$document = new DOMDocument;
//Load HTML in $contents variable
$document->loadHTML($contents);
//Get all links
if($links = $document->getElementsByTagName('a')) {
    //Loop through all links
    foreach($links as $node) {
        //Get link location (href)
        $link_href = $node->getAttribute('href');
        //Get link text
        $link_text = $node->nodeValue;
    }
}

?> 

I don’t think DOMDocument has a native, procedural equivalent. You have to use some other library then.

Sponsor our Newsletter | Privacy Policy | Terms of Service