-2

how to extract this html data table to csv file.

<table id="parts" class="parts-first horizontal">
    <tbody>
            <tr class="odd">
                <td class="score"><span class="rb">69</span</td>
                <td class="score part"><span class="p1_home">31</span></td>
            </tr>
            <tr class="even">
                <td class="score"><span class="rb">63</span></td>
                <td class="score part"><span class="p1_away">17</span></td>
            </tr>
    </tbody>
</table>

that gives those two lines data:
69 31
63 17
note that those data are refreshable,they change every one minute, so my csv file must contain something like that:

11,23
11,34

19,39
22,30

22,99
22,33
...

MRTgang
  • 113
  • 8
  • The CSV file has to be saved on a server (and then downloaded if you need it). But Javascript cannot edit/update files on your machine. So is this what you need? The Javascript gets these values from the DOM, sends them to a server, and then update the CSV file on the server? – blex Jun 12 '15 at 23:13
  • 1
    @blex he/she didn't ask that they are saved on their machine - just extract them from the HTML – nicholaswmin Jun 12 '15 at 23:15
  • this will be a second issue :)now all i want is the javascript code – MRTgang Jun 12 '15 at 23:16

1 Answers1

2

If you just need the code to get the data and form a CSV string from it, there you go. It outputs it to the console, but you might instead update the actual file with Ajax and PHP.

window.addEventListener('DOMContentLoaded', init, false);

function init(){
  var table = document.getElementById('parts');
  var csvString = table2csv(table, ',', false);
  console.log( csvString ); // Now you can save this string in a variable, or send it
}

function table2csv(table, delimitor, trailing){
  var data = '',
      rows = table.getElementsByTagName('tr');
  for(var i=0, l=rows.length; i<l; i++){
    var line = [],
        cells = rows[i].getElementsByTagName('td');
    for(var j=0, k=cells.length; j<k; j++){
      var value = cells[j].textContent.trim(' ');
      line.push(value);
    }
    data += line.join(delimitor) + (trailing?delimitor:'') + "\n";
  }
  return data + "\n\n";
}
The CSV should appear in your console.
<table id="parts" class="parts-first horizontal">
    <tbody>
            <tr class="odd">
                <td class="score"><span class="rb">69</span</td>
                <td class="score part"><span class="p1_home">31</span></td>
            </tr>
            <tr class="even">
                <td class="score"><span class="rb">63</span></td>
                <td class="score part"><span class="p1_away">17</span></td>
            </tr>
    </tbody>
</table>
blex
  • 24,941
  • 5
  • 39
  • 72