我有这个curl命令可以在命令行上创建wordpress post
curl --user admin:password -X POST http://localhost/wordpress/wp-json/posts --data "title=value1&content_raw=value2"
所以我想用PHP转换成Curl,这是我试过的代码
<?php
$username = "admin";
$password = "password";
$host = 'http://localhost/wordpress/wp-json/posts';
$data = array(
'title'=>'Test WP API',
'content_raw'=>'Hi this is a test WP API'
);
$process = curl_init($host);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
但是我不断收到此代码的错误。以下是CURL结果
HTTP/1.1 100 Continue
HTTP/1.1 400 Bad Request
Date: Tue, 10 Mar 2015 06:07:13 GMT
Server: Apache/2.4.9 (Win64) PHP/5.5.12
X-Powered-By: PHP/5.5.12
X-Pingback: http://localhost/jknsapc/xmlrpc.php
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Pragma: no-cache
X-Content-Type-Options: nosniff
Content-Length: 75
Connection: close
Content-Type: application/json; charset=UTF-8
[{"code":"json_missing_callback_param","message":"Missing parameter data"}]
你们可以指出我应该修复哪部分代码?更新:问题解决了。对于遇到与我相同问题的人,可以参考我编辑过的问题。
由于
我发现这段代码正常工作,我只需要json_encode数据并且不需要CURLOPT_HTTPHEADER
$username = "admin";
$password = "password";
$host = 'http://localhost/wordpress/wp-json/posts';
$data = array(
'title'=>'Test WP API',
'content_raw'=>'Hi this is a test WP API'
);
//json encode the data to pass via CURL
$data = json_encode($data);
$process = curl_init($host);
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);