首页 > 解决方案 > file_get_contents 到 json 数组

问题描述

我有使用以下代码通过 PHP 读取的 HTML 文件:

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

我创建了一个代码来将 html 代码分解为下面的 json::

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>

我需要转换$htmlcode成 JSON 数组。我如何合并这两者?

标签: javascriptphpjquery

解决方案


推荐阅读