在 PHP 中建立一個 Webhook

Sarwan Soomro 2023年1月30日 PHP PHP Webhook
  1. 在 PHP 中建立一個 Webhook
  2. 用 PHP 列印 Webhook 檔案
在 PHP 中建立一個 Webhook

Webhook 使用 JSON 和 XML 檔案格式處理,通常包含文字資料。使用者可以使用 PHP 函式來處理這些檔案。

在 PHP 中建立一個 Webhook

Webhook 通常採用 JSON/TEXT/XML 檔案格式。你可能希望這些檔案使用 PHP 指令碼進行控制。

你應該首先注意以下功能:

json_decode(file_get_contents("YOUR FILE PATH"), TRUE))

我們使用了 json_decode() 並在其中傳遞了兩個引數,一個 PHP 函式 file_get_contents() 和一個布林值。雖然這取決於使用者想要對這些檔案做什麼,但我們將向你展示如何在 PHP 中處理它們。

你可以建立、解碼或編碼這些檔案,或者稍後將它們儲存在資料庫中。

HTML 程式碼:

<!DOCTYPE html>
<body>
<form action="code.php" method="post" align="center">
<input type="submit" value="How do I create a webhook?" name="jsonfile" />
</form>
</body>
</html>

PHP 程式碼:

<?php
 if(isset($_POST['jsonfile'])){
$get = file_get_contents('example.json'); 
// example.json is for the demo, it can be any of your source data
$dump = print_r( $get, true );
$create_webhookfile = file_put_contents( 'webhook.log', $dump );
}
?>

輸出:

建立 Webhook PHP

程式碼如何工作

我們得到了帶有 file_get_contents() 函式的 JSON 演示檔案,然後我們將它儲存在 $get 變數中。

我們使用了帶有兩個引數的 print_r() 函式。在這種情況下,它是 $get 和布林值 TRUE

我們使用 file_put_contents() 函式轉儲陣列結果和 webhook.log 檔案字串。

此函式還需要至少兩個引數。

用 PHP 列印 Webhook 檔案

建立 webhook 檔案後,你可以使用以下 PHP 指令碼輕鬆列印它:

<?php
if($webhook = json_decode(file_get_contents("webhook.log"), true)){
$response = $webhook; 
 }
   echo "<pre>";
   print_r($response);
   echo "</pre>";
?>

輸出:

Array
(
    [Name] => ANY NAME
    [Surname] => ANY SURNAME
    [Sex] => male
    [Age] => 30
    [Location] => Array
        (
            [State] => Any State
            [City] => Any City
            [Street] => Any Street
            [Postal Code] => 278332766
        )
    [Contact] => Array
        (
            [0] => Array
                (
                    [type] => Office
                    [Number] => 286326832636
                )
        )
)

我們已經演示瞭如何使用 JSON 資料建立 webhook 檔案。

你將使用的資料來源可以是線上或任何 XML、文字和 JSON 檔案。

上面的 PHP 程式碼足以建立你的 webhook 檔案,同時列印它們或將它們儲存在 SQL 資料庫中,具體取決於你的特定要求。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Sarwan Soomro
Sarwan Soomro avatar Sarwan Soomro avatar

Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.

LinkedIn