我有一个如图所示的显示表单,如果单击“添加jadwal”按钮会自动保存到列表中。
询问: 单击按钮“ submit / simpan”后将如何列出数据数据表,成为数据json,如下所示? 谢谢
{
"mapel": [
{
"kelas": "1",
"hari": "Senin",
},
{
"kelas": "2",
"hari": "Senin",
},
]
}
答案 0 :(得分:0)
如果您能够获取表示HTML的DOMDocument对象,则只需递归遍历它并构建所需的数据结构。
将HTML文档转换为DOMDocument应该很简单:
function html_to_obj($html) {
$dom = new DOMDocument();
$dom->loadHTML($html);
return element_to_obj($dom->documentElement);
}
然后,简单遍历$ dom-> documentElement即可得到您所描述的结构,如下所示:
function element_to_obj($element) {
$obj = array( "tag" => $element->tagName );
foreach ($element->attributes as $attribute) {
$obj[$attribute->name] = $attribute->value;
}
foreach ($element->childNodes as $subElement) {
if ($subElement->nodeType == XML_TEXT_NODE) {
$obj["html"] = $subElement->wholeText;
}
else {
$obj["children"][] = element_to_obj($subElement);
}
}
return $obj;
}
测试用例
<html lang="en">
<head>
<title> This is a test </title>
</head>
<body>
<h1> Is this working? </h1>
<ul>
<li> Yes </li>
<li> No </li>
</ul>
</body>
</html>
header("Content-Type: text/plain");
echo json_encode(html_to_obj($html), JSON_PRETTY_PRINT);
输出
{
"tag": "html",
"lang": "en",
"children": [
{
"tag": "head",
"children": [
{
"tag": "title",
"html": " This is a test "
}
]
},
{
"tag": "body",
"html": " \n ",
"children": [
{
"tag": "h1",
"html": " Is this working? "
},
{
"tag": "ul",
"children": [
{
"tag": "li",
"html": " Yes "
},
{
"tag": "li",
"html": " No "
}
],
"html": "\n "
}
]
}
]
}