在 PHP 中创建一个 Webhook

Sarwan Soomro 2024年2月15日 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