How to transfer json data to html with php?

How to transfer json data to html with php?

$url="http://api.nytimes.com/svc/search/v1/article?format=json&query=usa&rank=newest&api-key=mykey"

when i type url in browser, it returns {"offset" : "0" , "results" : [{"body" : "A guide to cultural and recreational goings-on in and around the Hudson Valley. ...}]} how to put json data bodyin html? I mean how is itecho '<div class="body"></div>';

+3
source share
6 answers

First you need to get the file. You must use curl for this. In the example below, I used a function file_get_contents(), you can replace it. Use json_decode()to parse JSON for you.

$json = file_get_contents($url);
$data = json_decode($json);
echo $data->results[0]->body;

It will be an echo A guide to cultural....

+3
source

Use json_decode()in the contents of the file that you can get with file_get_contents($url), then you have an array that you can use to build HTML.

$url="http://api.nytimes.com/svc/search/v1/article?format=json&query=usa&rank=newest&api-key=mykey";
$dataRaw = file_get_contents($url);

if ($dataRaw) {
  $data = json_decode($dataRaw, true);
  foreach ($data['results'] as $cEntry) {
?>
  <div class="body">
      <?php echo $cEntry['body']; ?>
  </div>
<?php
  }
}
+2
source

, , , fopen() , ...

echo file_get_contents($url);
0

?

<?php

$url="http://api.nytimes.com/svc/search/v1/article?format=json&query=usa&rank=newest&api-key=mykey";
$json = file_get_contents($url);
echo $json;
0

Once you have loaded the JSON string in PHP, you can convert it to a PHP array using a function json_decode(). You can then print the corresponding array element in your HTML output, as with any other PHP variable.

0
source

Try the following:

$jsonDecoded = json_decode($yourJsonEncodedData);
echo $jsonDecoded->results->body;
0
source

Source: https://habr.com/ru/post/1784261/


All Articles