0

I have HTML file which I am reading via PHP using the below code:

$d = new DOMDocument;
$mock = new DOMDocument;
$d->loadHTML(file_get_contents('hydrocarbon2.htm'));
$body = $d->getElementsByTagName('body')->item(0);
foreach ($body->childNodes as $child){
$mock->appendChild($mock->importNode($child, true));
}

//echo $mock->saveHTML();
$htmlcode = $mock->saveHTML();
echo $htmlcode;

I have created a code to break the html code to json below::

var myRows = [];
var $headers = $("th");
var $rows = $("tbody tr").each(function(index) {
  $cells = $(this).find("td");
  myRows[index] = {};
  $cells.each(function(cellIndex) {
    myRows[index][$($headers[cellIndex]).html()] = $(this).html();
  });    
});
var myObj = {};
myObj.myrows = myRows;
alert(JSON.stringify(myObj));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>
</thead>
<tbody>
<tr> <td>Q</td><td>Desc.</td> </tr>
<tr> <td>Type</td><td>Multiple choice</td> </tr>
<tr><td>Option</td><td>image #####2</td><td>incorrect</td></tr>
<tr><td>Option</td><td>image #####2</td><td>incorrect</td></tr>
<tr><td>Option</td><td>image #####2</td><td>incorrect</td></tr>
<tr><td>Option</td><td>image #####2</td><td>incorrect</td></tr>

<tr><td>Solution</td><td>Some text / image</td></tr>
<tr><td>Marks</td><td>4</td><td>1</td></tr>
</tbody>
</table>

I need to convert $htmlcode into JSON array. How do I merge both of these?

halfer
  • 19,824
  • 17
  • 99
  • 186
user2828442
  • 2,415
  • 7
  • 57
  • 105
  • 1
    What is in `$htmlcode`? What is your expected output as a json array? – Nick Jan 19 '20 at 06:43
  • its showing html page as is on this php page, html page i have copied above in my question.. i want php page to provide same result as js is providing from html page – user2828442 Jan 19 '20 at 08:41
  • i have reached very near with different methods, this is my last barrier hopefully - help me here if you can- https://stackoverflow.com/questions/59808703/how-to-fetch-the-innerhtml-code-from-html-table-using-php – user2828442 Jan 19 '20 at 09:16

0 Answers0