-2

i have a data like

 <table>
   <tr>
     <th>title 1</th>
     <td>para1</td>
   </tr>
 </table>
 <table>
   <tr>
     <th>title 2</th>
     <td>para1</td>
     <td>para2</td>
     <td>para3</td>
   </tr>
 </table>
 <table>
   <tr>
     <th>title 3</th>
     <td>para1</td>
     <td>para2</td>
   </tr>
 </table>

now how can i take this data and make into an array..it will be really helpful if i can get a solution for this.

In my problem i have a table as shown above and want to store the data in a nested/ multidimensional array. All the solution above doesnot answer my question

thanks in advance

7

1 Answer 1

1

I think I know what you are looking for... It's actually pretty simple.

You want to iterate through the <table> tags first .. And subsequently iterate the children tr - tds.

I'd surround the tables with a surrounding div to make grabbing them much easier.

Then I'd use jQuery because the library makes it easy to choose children etc etc. Then for Storage into the database .. I'd "Json-ify" the array(s)

IE

$(document).ready(function() {
  myHTML = $('#myDiv').html();
});

var tableNumber = $('#myDiv').children('table').length;

var items = [];

for (i = 0; i < tableNumber; i++) {
  var title = $($("table tr th")[i]).html();

  var paras = [];

  $($("table tr")[i]).find('td').each(function() {
    paras.push($(this).html());
  });
  items.push(title, paras);
}

var outPut = JSON.stringify(items);

$('#jsonOut').html(outPut);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="myDiv">
  <table>
    <tr>
      <th>title 1</th>
      <td>para 1-1</td>
    </tr>
  </table>
  <table>
    <tr>
      <th>title 2</th>
      <td>para 2-1</td>
      <td>para 2-2</td>
      <td>para 2-3</td>
    </tr>
  </table>
  <table>
    <tr>
      <th>title 3</th>
      <td>para 3-1</td>
      <td>para 3-2</td>
    </tr>
  </table>
</div>

<br>
<pre>
 <div id="jsonOut">
 
 </div> 
</pre>

You can also view the FIDDLE

Hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

i am trying to parse that html in php
You're not being clear.. What EXACTLY are you doing? From beginning to end. Are you receiving that HTML from a database? Are you trying to do what I just did, but in PHP? Give us a 30,000 foot view of the process from beginning to end..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.