Skip to content Skip to sidebar Skip to footer

Convert A Selected Html Table To Json

Is it possible to convert just a selection of a HTML with multiple tables to JSON ? I have this Table:
2.11.2015 Montag

Solution 1:

You can use XPath to search for the class, and then create a new DOM document that only contains the results of the XPath query. This is untested, but should get you on the right track.

It's also worth mentioning that you can use foreach to iterate over the node list.

$document = new DOMDocument();
$document->loadHTML( $html );

$xpath = new DomXPath($document);
$tables = $xpath->query("//*[contains(@class, 'mon_list')]");
$tableDom = new DomDocument();
$tableDom->appendChild($tableDom->importNode($tables->item(0), true));

$obj = [];
$jsonObj = [];
$th = $tableDom->getElementsByTagName('th');
$td = $tableDom->getElementsByTagName('td');
$thNum = $th->length;
$arrLength = $td->length;
$rowIx = 0;

for ( $i = 0 ; $i < $arrLength ; $i++){
    $head = $th->item( $i%$thNum )->textContent;
    $content = $td->item( $i )->textContent;
    $obj[ $head ] = $content;
    if( ($i+1) % $thNum === 0){ 
        $jsonObj[++$rowIx] = $obj;
        $obj = [];
    }
}

Solution 2:

Another unrelated answer is to use getAttribute() to check the class name. Someone on a different answer has written a function for doing this:

functiongetElementsByClass(&$parentNode, $tagName, $className) {
    $nodes=array();

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            $nodes[]=$temp;
        }
    }

    return$nodes;
}

Post a Comment for "Convert A Selected Html Table To Json"