jane
jane

Reputation: 241

get json from a URL in php

I understand this is a common question.I want to know how do I fetch JSON from url in php.

the below file is where the .php file is :

<html>
<head>
    <?php
    // $url = "https://localhost:8666/web1/popupData/dataWeekly.php";
    // $emp = file_get_contents($url);

    $json_url = "https://localhost:8666/web1/popupData/dataWeekly.php";
    $json = file_get_contents($json_url);
    $emp = json_decode($json, TRUE);



    ?>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">

    <script type="text/javascript">
    $(document).ready(function(){
        var JSON = <?php echo json_encode($emp); ?>;

        $('.details').click(function(){
            var name = $(this).attr('id');

            $('#dialog').html('<p>Name : ' + name + '</p> <p>Dept : ' + JSON[name]['dept'] + '</p> <p>Age : ' + JSON[name]['age'] + '</p>');
            $('#dialog').dialog();
        });
    })
    </script>
</head>
<body>

<!-- Dialog Box -->
<div style="display: none;" id="dialog"></div>
<!-- Dialog Box -->

<?php
    foreach($emp as $key => $record)
    {
    ?>
        <ul id="<?php echo $key ?>" class="details">
            <li>Name: <?php echo $key ?></li>
            <li>Dept: <?php echo $record['dept'] ?></li>
        </ul>
    <?php
    }
?>

</body>
</html>

this is the current errors that I am getting as I run the above php file :

Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol in C:\xampp\htdocs\web1\popupData\mp.php on line 8

Warning: file_get_contents(): Failed to enable crypto in C:\xampp\htdocs\web1\popupData\mp.php on line 8

Warning: file_get_contents(https://localhost:8666/web1/popupData/dataWeekly.php): failed to open stream: operation failed in C:\xampp\htdocs\web1\popupData\mp.php on line 8

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\web1\popupData\mp.php on line 39

please help.

Upvotes: 1

Views: 4616

Answers (1)

msk
msk

Reputation: 481

Hi you can use either cURL or file_get_contents() to load data from URL

but if your using file_get_contents() then you must be enabled allow_url_fopen in your system & it's great for simple GET requests

cURL

cURL make http request just like opening an url in your browser

try using cURL

$json_url = "https://localhost:8666/web1/popupData/dataWeekly.php";  
$crl = curl_init();
curl_setopt($crl, CURLOPT_URL, $json_url);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, FALSE); 
$json = curl_exec($crl);
curl_close($crl);
$emp = json_decode($json, TRUE);

Upvotes: 2

Related Questions