[英]how do i convert HTML string to JSON with PHP
Is there a way to convert HTML string to JSON with PHP exactly like what toolslick.com html2json converter is doing.有没有一种方法可以将 HTML 字符串转换为 JSON 与 PHP 完全相同,就像 toolslick.Z4D236D9A2json50D102C5ZFE6AD1 转换器正在做的那样。
This is an example of the html string这是 html 字符串的示例
<html>
<body>
<table style="width: 100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</body>
</html>
I'm expecting a json like:我期待 json 像:
{
"html": {
"body": {
"table": {
"@style": "width: 100%",
"tr": [
{
"th": [
"Firstname",
"Lastname",
"Age"
]
},
{
"td": [
"Jill",
"Smith",
"50"
]
},
{
"td": [
"Eve",
"Jackson",
"94"
]
}
]
}
}
}
}
Any suggestion would be helpful thanks任何建议都会有帮助谢谢
If the HTML is valid you could try using SimpleXML and json_encode
to parse it into JSON:如果 HTML 有效,您可以尝试使用 SimpleXML 和
json_encode
将其解析为 JSON:
$xml = '<html>
<body>
<table style="width: 100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</body>
</html>';
$xmlObj = simplexml_load_string($xml);
echo json_encode($xmlObj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.