Created
July 10, 2019 12:43
-
-
Save rocketgeek/2f9fa1d36fd8fdcb788489e2cff4a276 to your computer and use it in GitHub Desktop.
Convert HTML DOM to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// https://stackoverflow.com/questions/23062537/how-to-convert-html-to-json-using-php | |
function html_to_obj( $html ) { | |
$dom = new DOMDocument(); | |
$dom->loadHTML( $html ); | |
return element_to_obj( $dom->documentElement ); | |
} | |
function element_to_obj( $element ) { | |
if ( isset( $element->tagName ) ) { | |
$obj = array( 'tag' => $element->tagName ); | |
} | |
if ( isset( $element->attributes ) ) { | |
foreach ( $element->attributes as $attribute ) { | |
$obj[ $attribute->name ] = $attribute->value; | |
} | |
} | |
if ( isset( $element->childNodes ) ) { | |
foreach ( $element->childNodes as $subElement ) { | |
if ( $subElement->nodeType == XML_TEXT_NODE ) { | |
$obj['html'] = $subElement->wholeText; | |
} elseif ( $subElement->nodeType == XML_CDATA_SECTION_NODE ) { | |
$obj['html'] = $subElement->data; | |
} else { | |
$obj['children'][] = element_to_obj( $subElement ); | |
} | |
} | |
} | |
return ( isset( $obj ) ) ? $obj : null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is there a function / foreach loop to export the original html back again? cheers!