我正在使用Restler 3库,我想从php发帖子。
我试过这种方式:
使用PHP cURL发布JSON数据
$data=array('name'=>'ddddd','email'=>'sdfsdf@sdgdsg');
$data_string = json_encode($data);
$ch = curl_init('http://192.168.0.101/Restler-3rc3-Stable/public/examples/_007_crud/Authors');
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))
);
$result = curl_exec($ch);
也是这样没有cURL :
//Pick your own method.by uncommenting one of the VERBS
//$method='GET';
$method='POST';
//$method='PUT';
//$method='DELETE';
$id=21;
$response_header=array();
//Point this URL to your own service
$url='http://192.168.0.101/Restler-3rc3-Stable/public/examples/_007_crud/Authors.php';
//READ
if ($method=='GET')
{
$url=$url.$id;
$data_array =array();
}
//CREATE
if ($method=='POST')
{
$data_array =array('id'=>$id);
}
//UPDATE
if ($method=='PUT')
{
$data_array =array('id'=>$id);
}
//DELETE
if ($method=='DELETE')
{
$url=$url.$id;
$data_array =array();
}
$data_array=array('name'=>'ddddd','email'=>'sdfsdf@sdgdsg');
$data = http_build_query($data_array);
$response=do_request($url,$data,NULL,$method,$response_header);
//Output the response and some debug info
echo 'Response Body='. $response;
echo '<hr><pre>Header= : ';
var_dump($response_header);
//Call the the rest service
function do_request($url, $data, $optional_headers = null , $method='GET', &$var)
{
$params = array('http' => array(
'method' => $method,
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
$var=$http_response_header;
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
echo "response".$response;
if ($response === false) {
$var=$http_response_header;
throw new Exception("Problem reading data from $url, $php_errormsg");
}
$var=$http_response_header;
return $response;
}
但两者都没有起作用。
我不知道我在这里遗失了什么。我正在尝试测试示例7“CRUD”
我是否必须将其包含在CRUD示例的index.php中?或者我必须在您的示例中放入index.php代码吗?
其中 index.php 是:
require_once '../../../vendor/restler.php';
use Luracast\Restler\Restler;
$r = new Restler();
$r->addAPIClass('Authors');
$r->handle();
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
<?php
$data = array("name" => "Another", "email" => "another@email.com");
$data_string = json_encode($data);
$ch = curl_init('http://restler3.luracast.com/examples/_007_crud/index.php/authors');
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))
);
$result = curl_exec($ch);
echo($result);
给你
{
"name": "Another",
"email": "another@email.com",
"id": 5
}