簡體   English   中英

從EXTERNAL HTML Table獲取數據到數組

[英]Get data from EXTERNAL HTML Table to an array

我需要將一些數據從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)

在您當前的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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM