简体   繁体   中英

Convert html table to text file using PHP/Javascript

I want to ask all of you for some help since I'm still new to web programming. So basically I have html table like this:

<table width='200' border='1'>
<TH>Year 1 Spring</TH>

<TR>
<TD>
<div id="y1f_0">one</div>
<div id="y1f_1">one</div>
</TD>
<TD>
<div id="y1s_0">two</div>
<div id="y1s_1">two</div>
</TD>
</TR>
</table>
<input  type="button" onclick="something">

and for example if I click the button, and it will save the table above and output/export it as a text file so later one I want get back that text file to export it back to the html table. I don't really know how to do this, should I use PHP? Really appreciate all your help.

you would use javascript ( jquery ) to collect the text and send it to a php file to save it on the server.

example of javascript( jquery ):

$( "#some_button" ).click(function( ){

    var file_text;

    file_text =  $( "#y1f_0" ).text( );
    file_text += $( "#y1f_1" ).text( );

    file_text += $( "#y1s_0" ).text( );
    file_text += $( "#y1s_1" ).text( );

    $.post( "save_file.php", file_data : file_text , function( data ){
        alert( data + " bytes have been written" );
    });
});

example of php script:

<?php
echo file_put_contents( "data.txt", $_POST[ "file_data" ] );
?>

Read up on jquery and php on http://w3schools.com

You'll find some more information there on $.post and other methods from javascript and php.

If you're new to web programming, it might take a little learning to get a hang of what you're trying to do. This is because you have to learn how to get the client script ( on the user's browser ) to connect to the server ( where the website files are ). If you don't have a server, you need to download one ( like apache ) or sign up to use one ( like godaddy.com ). With apache, you will have to do more learning but it's free. Otherwise, it's convenient to use a external server so that everything is already done for you.

Here's some quick notes on the rough handed example:

  • The '#' refers to the id of the element.

  • $( "#some_button" ).click is executed when the user clicks the div it's associated with.

Just wanted to add that in order to make the above code work i had to add the following curly brackets around the file_data : file_text

 $.post( "save_file.php", {file_data : file_text} , function( data ){
    alert( data + " bytes have been written" );
});

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