从EXTERNAL HTML表获取数据到数组

时间:2019-04-14 19:49:44

标签: javascript html arrays json html-table

我需要将html表(外部站点)中的某些数据保存到json文件中,以便使用该数据。

是否可以从外部HTML网站访问表(与我的代码示例不同)

有没有一种方法可以从数据中创建json文件(我需要数组或对象中的列?)并以某种方式保存它,以便我可以使用它?

我硬编码到我的站点中的数据的当前输出是:(我需要从外部站点访问)

https://i.gyazo.com/8bea34c222d8bba99c8705c8ca73c1a3.png

    <table>
      <tr>
        <th>A1</th>
        <th>A2</th>
        <th>A3</th>
        <th>A4</th>
        <th>A5</th>
      </tr>
      <tr>
        <td>B1</td>
        <td>B2</td>
        <td>B3</td>
        <td>B4</td>
        <td>B5</td>
      </tr>
      <tr>
        <td>C1</td>
        <td>C2</td>
        <td>C3</td>
        <td>C4</td>
        <td>C5</td>
      </tr>
      <tr>
        <td>D1</td>
        <td>D2</td>
        <td>D3</td>
        <td>D4</td>
        <td>D5</td>
      </tr>
      <tr>
        <td>E1</td>
        <td>E2</td>
        <td>E3</td>
        <td></td>
        <td>E5</td>
      </tr>
      <tr>
        <td>F1</td>
        <td></td>
        <td>F3</td>
        <td></td>
        <td></td>
      </tr>
    </table>

    <script>

    var columns = $('tr').first().children().map(function(i){
    return [
        $('tr').map(function(){
            return $(this).children().eq(i).text()
        }).get()
        ]
    }).get();

    localStorage

    console.log(columns)

1 个答案:

答案 0 :(得分:0)

在您当前的html / js文件中:

$.ajax({
        type: "POST",
        dataType: "json",
        url: "save_json_on_server.php",
        data: {my_columns:my_columns},
        success: function(data){
            alert('saved');
        },
        error: function(e){
            console.log(e.message);
        }
  });

save_json_on_server.php:在php中获取ajax以便在服务器上写入文件。

<?php
    $myjson_file = "my_columns_file.json";
    $fh = fopen($myjson_file, 'w') or die("can't open file");
    $str_data = $_POST["my_columns"];
    if(! fwrite($fh, $str_data ))
         die ("Failed to fwrite in the file : $myjson_file");
    fclose($fh);
    echo "success";
 ?>

要使用PHP从外部网站获取json文件:

<?php

$external_url = 'https://jsonplaceholder.typicode.com/posts';
$external_data = file_get_contents($external_url); 
$myjson_obj = json_decode($external_data); 

?>

<table>
<tbody>
<tr>
  <th>id</th>
  <th>name</th>
  <th>description</th>
</tr>
<?php foreach ($myjson_obj as $one_obj) : ?>
    <tr>
        <td> <?php echo $one_obj->id; ?> </td>
        <td> <?php echo $one_obj->title; ?> </td>
        <td> <?php echo $one_obj->body; ?> </td>
    </tr>
<?php endforeach; ?>
</tbody>
</table>
相关问题