-1

I need to save this json as a js file with a date with this format:

1-5-20_us_states.js

The json would then be inserted in the saved file within:

var data = ...json data... ;

I'm trying to follow this answer which it's ok to open the file but how to do the rest then?

Following that answer we should:

$url = "https://covidtracking.com/api/v1/states/daily.json";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
rob.m
  • 9,843
  • 19
  • 73
  • 162
  • if you want to save JSON, no need to decode it before saving it – Jaromanda X May 01 '20 at 03:36
  • @JaromandaX how would I insert it within the variable and save it as a js file? – rob.m May 01 '20 at 03:38
  • @JaromandaX updated the question, forgot to actually include the json link I'm talking about – rob.m May 01 '20 at 03:42
  • Does this answer your question? [How to generate .json file with PHP?](https://stackoverflow.com/questions/2467945/how-to-generate-json-file-with-php) – Anandhukrishna VR May 01 '20 at 03:43
  • "insert it within the variable" - you're writing to a file, you don't need to insert it into a variable ... just write `"var data =" . $json` to the file (if my PHP skills are correct) – Jaromanda X May 01 '20 at 03:43
  • 2
    @AnandhukrishnaVR - he doesn't WANT a JSON file, he wants a JS file – Jaromanda X May 01 '20 at 03:44
  • @JaromandaX exactly. Not thanks @ Anandhukrishna VR. Could anyone paste an answer if you know how to? – rob.m May 01 '20 at 03:45
  • do you know how to write a file in PHP? and why are you copying this data? – Jaromanda X May 01 '20 at 03:51
  • @JaromandaX Not really, but I could read something like this https://www.w3schools.com/php/php_file_create.asp thing is I don't know how to combine that with writing that json data within that var as per the question and save the js file with that date format I'm afraid – rob.m May 01 '20 at 03:53
  • `file_put_contents ("1-5-20_us_states.js", "var data =" . $json)` ? – Jaromanda X May 01 '20 at 03:55
  • @JaromandaX looks promising could you place that into a complete answer based on the question code please? Might be useful for future users too – rob.m May 01 '20 at 03:57

1 Answers1

1

As you're getting JSON, you don't need to decode it before writing it as a .js file since the JSON syntax is basically just like using javascript

prepend var data = to the string you get and you can write this to a file

Something like

$url = "https://covidtracking.com/api/v1/states/daily.json";
$json = file_get_contents($url);
file_put_contents ("1-5-20_us_states.js", "var data =" . $json);
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87