PHP:在 CURL 数据的关联数组中列出

问题描述 投票:0回答:1

我想从 此 API 发出请求,但遇到了一些麻烦。

示例请求是:

curl --location 'https://api.zoominfo.com/enrich/contact'
--header 'Content-Type: application/json'
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' --data '{"matchPersonInput": [{"firstName": "Henry","lastName": "Schuck","companyId": 346572700}],"outputFields": ["id","firstName","middleName","lastName"]}'

我正在 PHP 中实现这个,这是我的代码

//ZoomInfo IP Enrich
function zoominfo_email_enrich() {  
    $zoominfo_token = $_GET['zoominfo_token'];
    $response = "";     

    $data = array(      
        "matchPersonInput" => array( 
            "emailAddress" => "[email protected]",
        ),
        "outputFields" => array(
            "id",
            "firstName",
            "middleName",
        )
    );

    $postdata = json_encode($data); 

    $ch = curl_init("https://api.zoominfo.com/enrich/contact");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
    curl_setopt($ch,  CURLOPT_RETURNTRANSFER, 1);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: ' . $zoominfo_token));
    $response = curl_exec($ch);

    echo $response;
    die();
}

但是,此调用会导致错误:“MatchPersonInput 应该是一个列表”。

我也尝试过使用

$data = array(      
    "matchPersonInput" => list( 
        "emailAddress" => "[email protected]",
    )
);

这导致 WordPress 网站崩溃。

在 PHP 中格式化此数据以避免返回错误的正确方法是什么?

php wordpress curl
1个回答
0
投票

他们期望该键有多个值,请注意他们的示例输入,它用方括号括起来:

"matchPersonInput": [
    {"firstName": "Henry", "lastName": "Schuck", "companyId": 346572700}
]

这样,您可以指定多个记录:

"matchPersonInput": [
    {"firstName": "Henry", "lastName": "Schuck", "companyId": 346572700},
    {"firstName": "Mary", "lastName": "Wilbur", "companyId": 12345}
]

因此,即使您的代码中只有一条记录,您仍然需要将其放入列表中。用 PHP 术语来说,您需要一个数组的数组。我更喜欢短数组语法:

    $data = [
        "matchPersonInput" => [
            ["emailAddress" => "[email protected]"],
        ],
        "outputFields" => [
            "id",
            "firstName",
            "middleName",
        ]
    ];
© www.soinside.com 2019 - 2024. All rights reserved.