0

I want to use the Steam WEB API to generate some stats about games. In order to use the Steam WEB API I have to use a key that I am supposed to hide. I want to do all of the data processing with JavaScript, which doesn't allow me to hide the key. So I came up with this solution. I query the database in php, and pass the JSON object to JavaScript. My question is whether or not this is the preferred or best way to do this.

PHP:

<?php
$matchDetailsUrl  = "https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/? match_id=<MATCHID>&key=<KEY>";
$matchDetailsRaw  = file_get_contents($matchDetailsUrl);
$matchDetailsJson = json_decode($matchDetailsRaw);
?>

JavaScript:

<script>
var obj = JSON.parse('<?php echo json_encode($matchDetailsJson) ?>');
console.log(obj);
</script>
imbaer
  • 554
  • 3
  • 21

1 Answers1

0

There should be no need to re-encode all of the JSON data retrieved from the PHP file decode for JavaScript handling. You can write your JavaScript functions to do what they need to by passing results from the PHP decode, and call the JavaScript functions with PHP.

<?php
    echo "<script>functionName(" . $parameter1 . ", " . $parameter2 . ");</script>";
?>

Assuming $parameter1 and $parameter2 are PHP variables you made with some of the decoded JSON data from the API call, the page's HTML source will display this like a standard JavaScript function call with hard coded variable parameters being passed.

Your JavaScript function can do what it needs to do with the parameters given to it.

If your data handling is a "render once" type of affair, I would recommend writing the data handling functions in PHP rather than JavaScript to eliminate the confusion, but you can definitely pass what you need, as you need it between the PHP and JavaScript with out sending all the data.