简体   繁体   中英

Json request works in javascript but not in php

I'm trying to get a JSON object with PHP. When I try it with Jquery it works fine, but when I try the same with PHP, it returns me a timetout message.

Jquery code:

$(document).ready(function(){
    $.post("https://xxxxx/mig_search", {Keywords: 'test'}, function(result){
        var myObj = JSON.parse(result);
        $("body").html(result);
    });
});

PHP code:

$url = "https://xxxxx/mig_search";

$postdata = http_build_query(
    array(
        'Keywords' => 'teste',
    )
);

$options = array('http' =>
    array(
    'method' => 'POST',
    'header' => 'User-Agent: request',
    'content' => $postdata,
));

$ctx = stream_context_create($options);

$result = file_get_contents($url, false, $ctx);
if (!empty($result)) {
    echo $result;
} else {
    echo "Nao funcionou!";
}
die;

Try this below code

$postdata = http_build_query(array ('Keywords' => 'teste'));

$options = array (
'http' => array (
    'method' => 'POST',
    'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
        . "Content-Length: " . strlen($postdata) . "\r\n",
    'content' => $postdata
    )
);

Try to add a Content-Header:

'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
            . "Content-Length: " . strlen($postdata) . "\r\n",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM