How to RAW POST huge XML file with curl - PHP

前端 未结 2 911
-上瘾入骨i
-上瘾入骨i 2020-12-18 07:33

is there a way of doing

curl -X POST -H \"Content-Type:application/xml\" --data @myfile.xml http://example.com

but directly in PHP?

<
2条回答
  •  被撕碎了的回忆
    2020-12-18 08:25

    I had a similar problem trying to feed huge ingestion files to elasticsearch's bulk API from PHP, until I realized that the bulk API endpoint accepted PUT requests. Anyway, this code performs POST requests with huge files:

    $curl = curl_init();
    curl_setopt( $curl, CURLOPT_PUT, 1 );
    curl_setopt( $curl, CURLOPT_INFILESIZE, filesize($tmpFile) );
    curl_setopt( $curl, CURLOPT_INFILE, ($in=fopen($tmpFile, 'r')) );
    curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'POST' );
    curl_setopt( $curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ] );
    curl_setopt( $curl, CURLOPT_URL, $url );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
    $result = curl_exec($curl);
    curl_close($curl);
    fclose($in);
    

    Here, $tmpFile is the full path of the file containing the request body.

    NOTE: The important part is setting CURLOPT_CUSTOMREQUEST to 'POST' even though CURLOPT_PUT is set.

    You'd have to adapt the Content-Type: header to whatever the server is expecting.

    Using tcpdump, I could confirm the request method to be POST:

    POST /my_index/_bulk HTTP/1.1
    Host: 127.0.0.1:9200
    Accept: */*
    Content-Type: application/json
    Content-Length: 167401
    Expect: 100-continue
    
    [...snip...]
    

    I'm using packages libcurl3 (version 7.35.0-1ubuntu2.5) and php5-curl (version 5.5.9+dfsg-1ubuntu4.11) on Ubuntu 14.04.

提交回复
热议问题