这是用PHP在post-request中发送JSON的最好、最快的方式


Which is the best and fastest way to send JSON in post request in PHP?

我是android开发人员,对php有一定的了解。我需要在php中发布请求。我找到了两种方法来实现它。

1.使用CURL

$url = "your url";    
$content = json_encode("your data to be sent");
$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);

2.使用简单Post(file_get_contents)

$options = array(
  'http' => array(
    'method'  => 'POST',
    'content' => json_encode( $data ),
    'header'=>  "Content-Type: application/json'r'n" .
                "Accept: application/json'r'n"
    )
);
$context  = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );

但是,我只想知道哪种方法更好、更有效,为什么?是否存在任何服务器/浏览器或任何与平台相关的问题?或者还有其他技术可以做到这一点吗?欢迎提出建议。感谢

实现的最佳方式

  1. 使用CURL

因为这是最快的&更可靠。。

如果您只是从Android JAVA代码的调用启动的PHP脚本中发送JSON回复,那么最简单的(可能是最快的)就是从PHP脚本中echo JSON字符串。

<?php
    // read the $_POST inputs from Android call
    // Process whatever building an array 
    // or better still an object containing all
    // data and statuses you want to return to the
    // android JAVA code
    echo json_encode($theObjectOrArray);
    exit;

通过这种方式,它都是同一个帖子/响应的一部分。如果你参与了CURL,你就打破了简单的生命周期。