How to get json fom url in php

I am trying to make php page tp print json data for this im using one parator for which I needed to extract json from another url.I used the code specified in other stackoverflow ans, but it always gave 0.I tried everything but it always gives 0.My php code:

<?php
if(isset($_POST['add']))
{
require_once('loginConnect.php');



 $bookname=$_POST['bookname'];




$url = "http://example/star_avg.php?bookName=$bookname";
$json = file_get_contents($url);
$json_data = json_decode($json,TRUE);




 echo 'data' + $json_data->results[0]->{'num'};

?>

My json data from another url:   {"result":[{"avg":"3.9","num":"3"}]}

+4
source share
1 answer

You see printed 0because you are adding +between string data and a nonexistent property. In PHP, to concatenate strings, do not use +; use the dot operator instead.

, true json_decode, , , . [], -> .

$json_data = json_decode($json,TRUE);
$num = $json_data['result'][0]['num']; //<- array notation
echo 'data: '.$num; //prints data: 3

+7

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


All Articles