CLI CURL -> PHP CURL

后端 未结 3 702
深忆病人
深忆病人 2020-12-21 06:22

How can I translate this curl command so that it works in a PHP script?

curl --request POST --data-binary \'@import.xml\' --header \"Content-Type: applicatio         


        
相关标签:
3条回答
  • 2020-12-21 06:50
    $data = array('file'=> '@' . $filename);                    
    

    You need to prepend the filename with a '@' to tell CURL it's actually a filename and not just a string. The headers are not required either, as CURL will fill them in itself.

    0 讨论(0)
  • The correct thing would be to read the file into a string and then provide that string to the CURLOPT_POSTFIELDS options. That feature of reading into a string is not provided by libcurl but is done by the command line client and I don't think the PHP/CURL binding offers the equivalent.

    The command line uses --data-binary which corresponds to a CURLOPT_POSTSFIELDS with a string, not a hash array as the array will turn the post in to a multipart post (which the command line does with -F, --form). Also, the custom request set to POST is totally superfluous.

    Usually, running the command line with "--libcurl test.c" is a good way to get a first draft version of a C program using the C API, but as the PHP API is very similar that should work as decent start in most cases.

    Edit: and custom changing/providing the "Content-Length:" header is never a good idea unless you know perfectly well what you're doing. libcurl will always provide one that is generated based on the data you pass on to it.

    0 讨论(0)
  • 2020-12-21 06:57

    Try this:

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/atom+xml'
        ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 'http://siteurl.com');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));  
    curl_exec($ch);
    
    0 讨论(0)
提交回复
热议问题