【问题标题】:POST JSON string with PHP and CURL to a php page and get response将带有 PHP 和 CURL 的 JSON 字符串发布到 php 页面并获得响应
【发布时间】:2018-05-30 18:08:41
【问题描述】:

我正在尝试学习如何通过 CURL 将 PHP 发布到另一个 PHP 页面并阅读响应。

我有 2 页。第一个是test.php

<?php
$array['User'] = array();
$array['User']['AppId'] = 'sdfgfd9-sdfgsdf-sdfgfdgfgff';
$array['User']['UserName'] = 'me@example.co.uk';
$array['User']['Token'] = 'fsdgf5-455g-223ee-bggg-asdsadsda';
$array['User']['Timestamp'] = '2018-05-30BST16:28:293600';

$url = "https://www.myurl.co.uk/api/index.php";    
$content = json_encode($array['User']);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) 
{
   die("Error: call to URL $url failed with status $status, response 
  $json_response, curl_error " . curl_error($curl) . ", curl_errno " . 
  curl_errno($curl));
}

curl_close($curl);

$response = json_decode($json_response, true);
echo $response;
?>

然后在页面上我只是从我那里获取数据;

<?php
$userArray = array();   
$userArray = trim(file_get_contents("php://input"));
echo json_decode($userArray, true);
?>

当我在 test.php 上运行脚本时,我得到的响应是;

Error: call to URL https://www.myurl.co.uk/api/index.php failed with status 200, response Array, curl_error , curl_errno 0

我对错误的理解不够,无法理解要进行哪些更改才能使其正常工作?

【问题讨论】:

  • 200 不是错误码,是成功码。
  • 再试200次成功,报告结果
  • 我没有意识到围绕输出的 if 语句不正确。这一切都很好,谢谢你

标签: php arrays json curl


【解决方案1】:

尝试: curl_setopt($curl, CURLOPT_HTTPHEADER, 大批( '方法' => 'POST', 'header' => 'Content-Type: application/json' 。 “\r\n” . '内容长度:'。 strlen($data_string) 。 "\r\n", '内容' => $data_string, );

或类似

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    相关资源
    最近更新 更多