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;
}