Jonhas
Jonhas

Reputation: 125

Parse HTML table to database format with PHP

I always had to show a table using the content of a database, but never backwards. One company just published a HTML table with some useful information, however they are not offering a database file, just the table.

It's a normal table. Just to clarify, something like:

<table>
<tbody>
<tr>
<td>ELEMENT 1</td>
<td>ELEMENT2</td>
<td>ELEMENT 3</td>
<td>ELEMENT 4</td>
</tr>
</tbody>
</table>

What I would like to do is create a database with that date, being ELEMENT 1 the 'id', and the rest, information related with that id. I don't know how to create a bucle to get all the elements from that table, and insert them into the database.

What I'm asking is if there is a way to parse that information, so I can do what I want. I'm not asking the code to insert it into the database or so, just how should I parse that information. Thanks!

Upvotes: 1

Views: 1431

Answers (1)

Davide Pastore
Davide Pastore

Reputation: 8738

You need to do this:

 <?php
  //Load the DOM Document
  $doc = new DOMDocument();
  $doc->loadHTMLFile("filename.html");

  //Find td elements
  $xpath = new DOMXPath($doc);
  $query = '//your/path/to/table/tbody/tr/td';
  $entries = $xpath->query($query);

  $id = $entries->item(0);
  $item1 = $entries->item(1);
  $item2 = $entries->item(2);
  $item3 = $entries->item(3);

  //You query here...
 ?>

References: DOM

Upvotes: 1

Related Questions