1

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;
3
  • You should use Content-type: application/x-www-form-urlencoded in the header Commented Oct 8, 2018 at 12:46
  • Why not use curl? Commented Oct 8, 2018 at 12:53
  • Thanks for the answer guys. I'm going to try also with curl. Commented Oct 8, 2018 at 13:29

2 Answers 2

1

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
    )
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer! Your code works fine also with PHP when I tried with the JSON from this page w3schools.com/js/demo_file.php. But when I try with the endpoint that I have on my server made with python, it doesn't work, but it works only with the javascript code. Do you have any idea what it could be?
0

Try to add a Content-Header:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.