【问题标题】:How to call json from php如何从php调用json
【发布时间】:2016-01-28 10:56:42
【问题描述】:

我编写了一个 php 代码,它应该打印一个 json 调用的响应。但我得到 NULL 输出。我已经检查了我的 json 调用在 restclient 上工作正常。

这是我的代码

<?php

    $username = "user";
    $password = "password";

    $postData = array(
            'username' => $username,
            'password' => $password,
            'msisdn' => "111111111"
            );

    $ch = curl_init('http://ip:<port>/xxx/yyy/zzz');

    curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
    ));

    // Send the request
    $response = curl_exec($ch);

    // Check for errors
    if($response === FALSE){
    die(curl_error($ch));
    }

    // Decode the response
    $responseData = json_decode($response, TRUE);

    // Print the date from the response
    echo $responseData['published'];

    var_dump($responseData);

    ?>

提前致谢。

【问题讨论】:

  • var_dump($response) 看看你得到了什么回应。
  • 你检查过你的 $response 是否真的包含 JSON 代码,如果是,它是否有效?
  • 试试print_r(json_last_error());
  • var_dump($response) 给出 HTTP 状态 500,但有以下异常 - javax.servlet.ServletException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "username"
  • @Pemapmodder print_r(json_last_error()); 给出了 4 作为输出,这是语法错误吗?

标签: php json api curl


【解决方案1】:

试试:

$responseData = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new \RuntimeException('Invalid JSON.');
}

【讨论】:

  • 我收到了Stack trace: #0 {main} thrown in 异常
  • 表示你没有收到json,或者是无效的json。
【解决方案2】:

好的,我已经解决了我的问题并重新编写了代码。我实际上没有在 json 字段中提供正确形式的用户名和密码,这真是一个愚蠢的错误。 我在这里提供我的更新代码 `

$data = array("user" => "$username", "pass" => "$password", "msisdn" => "$msisdn");
$data_string = json_encode($data);

$ch = curl_init('http://ip:port/call_center/account/general');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo $result;


?>`

谢谢大家。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2013-09-29
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 2018-03-16
    相关资源
    最近更新 更多