How to convert HTML to JSON using PHP

0 votes

How to convert JSON to HTML using JsontoHtml library. Now,I need to convert present HTML to JSON as shown in this site. When looked into the code I found the following script:

<script>
$(function(){

    //HTML to JSON
    $('#btn-render-json').click(function() {

        //Set html output
        $('#html-output').html( $('#html-input').val() );

        //Process to JSON and format it for consumption
        $('#html-json').html( FormatJSON(toTransform($('#html-output').children())) );
    });

});

//Convert obj or array to transform
function toTransform(obj) {

    var json;

    if( obj.length > 1 )
    {
        json = [];

        for(var i = 0; i < obj.length; i++)
            json[json.length++] = ObjToTransform(obj[i]);
    } else
        json = ObjToTransform(obj);

    return(json);
}

//Convert obj to transform
function ObjToTransform(obj)
{
    //Get the DOM element
    var el = $(obj).get(0);

    //Add the tag element
    var json = {'tag':el.nodeName.toLowerCase()};

    for (var attr, i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
        attr = attrs[i];
        json[attr.nodeName] = attr.value;
    }

    var children = $(obj).children();

    if( children.length > 0 ) json['children'] = [];
    else json['html'] = $(obj).text();

    //Add the children
    for(var c = 0; c < children.length; c++)
        json['children'][json['children'].length++] = toTransform(children[c]);

    return(json);
}

//Format JSON (with indents)
function FormatJSON(oData, sIndent) {
    if (arguments.length < 2) {
        var sIndent = "";
    }
    var sIndentStyle = "  ";
    var sDataType = RealTypeOf(oData);

    // open object
    if (sDataType == "array") {
        if (oData.length == 0) {
            return "[]";
        }
        var sHTML = "[";
    } else {
        var iCount = 0;
        $.each(oData, function() {
            iCount++;
            return;
        });
        if (iCount == 0) { // object is empty
            return "{}";
        }
        var sHTML = "{";
    }

    // loop through items
    var iCount = 0;
    $.each(oData, function(sKey, vValue) {
        if (iCount > 0) {
            sHTML += ",";
        }
        if (sDataType == "array") {
            sHTML += ("\n" + sIndent + sIndentStyle);
        } else {
            sHTML += ("\"" + sKey + "\"" + ":");
        }

        // display relevant data type
        switch (RealTypeOf(vValue)) {
            case "array":
            case "object":
                sHTML += FormatJSON(vValue, (sIndent + sIndentStyle));
                break;
            case "boolean":
            case "number":
                sHTML += vValue.toString();
                break;
            case "null":
                sHTML += "null";
                break;
            case "string":
                sHTML += ("\"" + vValue + "\"");
                break;
            default:
                sHTML += ("TYPEOF: " + typeof(vValue));
        }

        // loop
        iCount++;
    });

    // close object
    if (sDataType == "array") {
        sHTML += ("\n" + sIndent + "]");
    } else {
        sHTML += ("}");
    }

    // return
    return sHTML;
}

//Get the type of the obj (can replace by jquery type)
function RealTypeOf(v) {
  if (typeof(v) == "object") {
    if (v === null) return "null";
    if (v.constructor == (new Array).constructor) return "array";
    if (v.constructor == (new Date).constructor) return "date";
    if (v.constructor == (new RegExp).constructor) return "regex";
    return "object";
  }
  return typeof(v);
}
</script>

How to do that?

Jun 19, 2020 in Java-Script by kartik
• 37,520 points
7,713 views

1 answer to this question.

0 votes

Hello @kartik,

If you are able to obtain a DOMDocument object representing your HTML, then you just need to traverse it recursively and construct the data structure that you want.

Converting your HTML document into a DOMDocument should be as simple as this:

function html_to_obj($html) {
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    return element_to_obj($dom->documentElement);
}

Then, a simple traversal of $dom->documentElement which gives the kind of structure you described could look like this:

function element_to_obj($element) {
    $obj = array( "tag" => $element->tagName );
    foreach ($element->attributes as $attribute) {
        $obj[$attribute->name] = $attribute->value;
    }
    foreach ($element->childNodes as $subElement) {
        if ($subElement->nodeType == XML_TEXT_NODE) {
            $obj["html"] = $subElement->wholeText;
        }
        else {
            $obj["children"][] = element_to_obj($subElement);
        }
    }
    return $obj;
}

Hope this is helpful!!

answered Jun 19, 2020 by Niroj
• 82,840 points

Related Questions In Java-Script

0 votes
1 answer

How to send JSON data from Javascript to PHP?

Hello @kartik, PHP has a built in function ...READ MORE

answered Jul 6, 2020 in Java-Script by Niroj
• 82,840 points
6,899 views
0 votes
1 answer

How to convert a ruby hash object to JSON?

Hello @kartik, You can also use JSON.generate: require 'json' JSON.generate({ foo: ...READ MORE

answered Jul 24, 2020 in Java-Script by Niroj
• 82,840 points
12,664 views
0 votes
1 answer

How to decode HTML entities using jQuery?

Hello @kartik, To encode: $("<textarea/>").html('<a>').html(); ...READ MORE

answered Sep 2, 2020 in Java-Script by Niroj
• 82,840 points
7,588 views
0 votes
1 answer

How to create HTML elements using jQuery?

Hello @kartik,  if you're doing $('<div>'), jQuery will also ...READ MORE

answered Sep 18, 2020 in Java-Script by Niroj
• 82,840 points
1,132 views
0 votes
1 answer

How can we Create Multiple Where Clause Query Using Laravel Eloquent?

Hii, You can use Conditions using Array: $users = User::where([ ...READ MORE

answered Mar 30, 2020 in Laravel by Niroj
• 82,840 points
16,735 views
0 votes
1 answer

How to send email using php?

Hello @kartik 1.) Download PHPMailer, open the zip file ...READ MORE

answered Apr 1, 2020 in PHP by Niroj
• 82,840 points
1,359 views
0 votes
1 answer

Where to register Facades & Service Providers in Lumen?

Hello, To register a facade with an alias, ...READ MORE

answered Apr 6, 2020 in Laravel by Niroj
• 82,840 points
4,473 views
0 votes
1 answer

How can I update NodeJS and NPM to the next versions?

Hello @kartik, First check your NPM version npm -v 1).Update ...READ MORE

answered May 5, 2020 in Java-Script by Niroj
• 82,840 points
1,031 views
+1 vote
2 answers

How to convert entire div data into image and save it into directory without using canvas?

Hello @kartik, You can try the sample code ...READ MORE

answered Apr 29, 2020 in Java-Script by Niroj
• 82,840 points
72,882 views
0 votes
1 answer

How to Store PHP variable with HTML in JavaScript in Laravel Blade Template?

Hello @kartik, The double curly brackets {{ }} will always ...READ MORE

answered Jun 11, 2020 in Java-Script by Niroj
• 82,840 points
17,291 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP