2

我有这个 curl 命令可以在命令行上创建 wordpress 帖子

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);
4

0 回答 0