【发布时间】:2017-11-02 17:15:31
【问题描述】:
我正在尝试从 php 脚本运行 curl 命令,但它没有按预期工作。问题出在 curl 命令或我用 .htacccess 文件编写的 url 重写规则中。
curl 命令文件中的代码:我只是尝试使用此命令发布数据并期望返回一个数组。
<?php
$data=array(
'product_name' =>'Television',
'price' => 1000,
'quantity' => 10,
'seller' =>'XYZ Traders'
);
$url = 'http://localhost/API2/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
curl_close($ch);
$response=json_decode($response_json, true);
echo $response;
?>
我的 .htaccess 文件用于 url 重写,这意味着 http://localhost/API2/products 应该用于 CRUD 操作。网址规则为:
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^products/?$ products.php [NC,L]
RewriteRule ^products/([0-9]+)/?$ products.php?product_id=$1 [NC,L]
因此,如果您可以在我运行 curl 命令 file.php 时帮助找到问题,它不会返回任何内容,也不会执行代码。
【问题讨论】:
-
$response_json 中有什么?您是否尝试过回应?
-
$request_method=$_SERVER["REQUEST_METHOD"]; switch($request_method) { case 'POST': $response=array('status' => 1, 'status_message' =>'产品添加成功。'); header('Content-Type: application/json');回声 json_encode($response); default: // 无效的请求方法标头("HTTP/1.0 405 Method Not Allowed");休息; }
-
我没有得到你想要的这个评论男人
-
在我的其他文件中是这样的。我编辑了它。我使用 switch 语句,具体取决于它需要进入它并返回数组的 request_method。
-
重点是在使用 json_decode 之前你必须检查 curl 的原始响应并检查里面的内容