Skip to content

Instantly share code, notes, and snippets.

@rocketgeek
Created July 10, 2019 12:43
Show Gist options
  • Save rocketgeek/2f9fa1d36fd8fdcb788489e2cff4a276 to your computer and use it in GitHub Desktop.
Save rocketgeek/2f9fa1d36fd8fdcb788489e2cff4a276 to your computer and use it in GitHub Desktop.
Convert HTML DOM to JSON
<?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;
}
@kingozorg
Copy link

is there a function / foreach loop to export the original html back again? cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment