简体   繁体   中英

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.

This is an example of the html string

<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:

{
  "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:

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

https://3v4l.org/TZ4BP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM