转换cURL for Guzzle发送XML文件

时间:2014-08-06 14:02:29

标签: php curl guzzle

我正在尝试转换此cURL脚本以将其与PHP和Guzzle一起使用。我已经能够设置如下所示的cookie,但我之后无法发送我需要的xml文件。

cURL脚本

# First, we need to get the cookie
curl [-k] –dump-header <header_file> -F “action=login” -F “username=<username>” -F “password=<password>” https://<website_URL>
# Then, we can use that cookie to upload our orders

# XML Order Upload
curl -b <header_file> -F “import=@<order_file>” http://<website_URL>/importXMLOrder.php

这就是我设置cookie的方法。我不确定下一部分实际发送我的xml文件是什么。

        $client = new \GuzzleHttp\Client();

    $response = $client->post('http://website/login.php', array(
            'body' => array(
                'username' => 'xxxxx',
                'password' => 'xxxxxx'
            ))
    );

我也试过这个。但是,我收到一条错误消息:

Call to undefined method GuzzleHttp\Message\Response::send()


    $request = $client->post('http://website.com/import.php', array(
        'body' => array(
            'file_filed' => fopen('orders.xml', 'r')
        )));
    $response = $request->send();
    $data = $response->xml();

    print_r($data);

更新

    $request = $client->createRequest('POST','http://website.com/import.php', array(
        'body' => array(
            'file_filed' => file_get_contents('orders.xml', 'r')
        )
    ));
    $response = $client->send($request);

    //var_dump($response); die;
    $data = $response->xml();

    echo '<pre>';
    print_r($data);

1 个答案:

答案 0 :(得分:1)

看起来你正在从错误的班级调用send()send()\GuzzleHttp\Client的一种方法。所以你需要做$client->send()

但是,$client->post()会在创建请求后立即发送请求。如果您想使用send(),则需要将post()替换为createRequest(),如下所示:http://guzzle.readthedocs.org/en/latest/clients.html#creating-requests

fopen()的调用也会遇到问题,该调用会返回文件句柄而不是内容。请改为file_get_contents()

修改

为了设置auth cookie,你需要一个cookie jar。请尝试以下方法:

$client = new \GuzzleHttp\Client();
$auth = $client->post('http://website/login.php', array(
        'body' => array(
            'username' => 'xxxxx',
            'password' => 'xxxxxx'
        ),
        'cookies' => true
        ));

使用相同的Client

$request = $client->createRequest('POST','http://website.com/import.php', array(
    'body' => array(
        'file_filed' => file_get_contents('orders.xml')
    ),
    'cookies' => true
    ));
$response = $client->send($request);

//var_dump($response); die;
$data = $response->xml();

echo '<pre>';
print_r($data);