user2951249
user2951249

Reputation: 87

Issue Retrieving JSON Content from URL in PHP with Curl

I'm trying to retrieve the price values from this url.

I can see the content when inspecting the price element in Firefox and it seems to be using json. Here's what I've been trying with curl in php.

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HEADER, 1,
    CURLOPT_URL => 'https://www.speedway.com/Pages/GasPriceSearch.aspx?lat=40.4172871&lng=-82.90712300000001&st=ohio'
]);

$resp = curl_exec($curl);
curl_close($curl);
var_dump(json_decode($resp));

The result I always receive from this is NULL so it doesn't seem that I'm getting any json content in return.

I have tried setting a useragent and that doesn't change anything. I also thought that maybe the server is preventing me from receiving what I want. I tried adding

$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

and outputting the result of that, but I got a 200 so I don't think that's an issue either. If I just echo $resp I receive all the HTML content, but the json data isn't in there.

I'm no expert to what I'm trying to do, so I'm sure I'm missing something, but not sure what. Any ideas?

Upvotes: 1

Views: 83

Answers (2)

worldofjr
worldofjr

Reputation: 3886

You have a syntax error.

CURLOPT_HEADER, 1,

should be

CURLOPT_HEADER => 1,

or just remove it completely, because it isn't required.

But the web address you're getting the data from isn't a JSON page anyway.

Upvotes: 1

Alexis King
Alexis King

Reputation: 43842

The URL you provided is the webpage itself, not the JSON data. The JavaScript in that page loads the JSON data from somewhere else, specifically, from here:

https://www.speedway.com/_layouts/Speedway/GasPrices.aspx?lat=40.4172871&lng=-82.90712300000001&st=ohio

Use that instead, and your code should retrieve the correct data.

Upvotes: 1

Related Questions