【问题标题】:Get data from EXTERNAL HTML Table to an array从外部 HTML 表中获取数据到数组
【发布时间】:2019-09-04 20:36:08
【问题描述】:

我需要将一些数据从 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)

【问题讨论】:

  • 您可以使用浏览器控制台或用户脚本在其他人的网站上运行您的 Javascript,如果这就是您的要求..?从那里,你可以做任何事情。如果其他网站有 CORS 限制(就像大多数网站一样),您将无法在客户端直接连接到它
  • 让我们看看这个例子:quora.com/…

标签: javascript html arrays json html-table


【解决方案1】:

在您当前的 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 以便在 server.side 上写入文件:

<?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>

【讨论】:

    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2019-04-13
    • 2021-03-23
    • 2013-01-08
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多