开发者

cURL with PHP and JSON

开发者 https://www.devze.com 2023-03-20 07:22 出处:网络
I wish to mimic, using CURL with PHP, the operation of a website that retrieves data using an AJAX POST.

I wish to mimic, using CURL with PHP, the operation of a website that retrieves data using an AJAX POST.

Normally when I'm viewing POST requests using Firebug you will see variable/value pairs, but in this case all you see is a single JSON string. E.g.

{"refId":"14536"}

Is there a way to mimic this request using CURL? I've looked at CURL but as far as I can see the CURLOPT_POSTFIELDS parameter has to be a query string made up of one or more name/value.

Here is my test code with a normal POST requ开发者_如何学Pythonest using a single name/value pair. I'd like to modify it to do the above.

$curlOptions = array(
    CURLOPT_RETURNTRANSFER => true,     // return web page
    CURLOPT_HEADER         => false,    // don't return headers
    CURLOPT_ENCODING       => "",       // handle all encodings
    CURLOPT_USERAGENT      => "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3",
    CURLOPT_CONNECTTIMEOUT => 600,      // timeout on connect
    CURLOPT_TIMEOUT        => 600,      // timeout on response
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => 'var1=113',
    CURLOPT_URL            => "http://localhost/t4.php"
);

$curlCh      = curl_init();
curl_setopt_array( $curlCh, $curlOptions );
$fileContents = curl_exec( $curlCh );
$curlErr     = curl_errno( $curlCh );
$curlErrmsg  = curl_error( $curlCh );

if( $curlErr ) echo "CURL ERROR:</b> $curlErr  $curlErrmsg";
echo $fileContents; //check worked
curl_close( $curlCh );


How about something like:

$postData = json_encode(array('refId' => '14536'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
0

精彩评论

暂无评论...
验证码 换一张
取 消