从REST API获取发布的数据

时间:2018-08-06 14:07:40

标签: php rest

我为我的网站创建了一个剩余的APi。 GET方法工作正常。对于POST方法,api不会将数据发布回去。我写了这段代码,但是由于     注意:尝试获取非对象的属性

$response = file_get_contents('http://myapi.com/object/post.php');
$data = json_decode($response);

$object->id = $data->id;
$object->name = $data->name;

2 个答案:

答案 0 :(得分:0)

您可以为file_get_contents URL简化GET,但是要从POST URL获取数据,您需要使用CURL:

<?php

$post = [
    'postData1' => 'datavalue1',
    'postData2' => 'datavalue2'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://myapi.com/object/post.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$data = json_decode($response);

$object->id = $data->id;
$object->name = $data->name;

答案 1 :(得分:0)

PHP文档中说明了在file_get_contents中使用POST。在手册页http://php.net/manual/en/function.file-get-contents.php中:

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>