Php json url https

How to Pass JSON Data in a URL using CURL in PHP ?

In this article, we will see how to pass the JSON Data in a URL using CURL in PHP, along with understanding the different ways for passing the data in a URL through the illustrations. The cURL stands for client URL, which allows us to connect with other URLs & use their responses in our code, i.e., it is a tool for sending and getting files using URL syntax. The cURL facilitates the way that can hit a URL from our code to get an HTML response from it. The cURL is also used in command lines or scripts for data transfer. Here, we need to pass JSON data in a URL using cURL in PHP and handle the POST request. This task can be accomplished with the help of the following ways:

We will explore all the above approaches & understand them through examples.

Syntax for passing JSON data in a URL using cURL:

Approach for POST Request:

  • We need to specify the URL, where the JSON data need to be sent.
  • Using curl_init(), we initialize cURL.
  • Put JSON data in a PHP array and set up JSON data.
  • And using json_encode() encode it into JSON string.
  • Setting the options for the cURL.
    • Fetching $url using CURLOPT_URL.
    • Switching request type from get to post using CURLOPT_POST.
    • Now attach the encoded string in the post field using CURLOPT_POSTFIELDS.
    • Setting the curl option RETURNTRANSFER to true so that it returns the response instead of just outputting it.
    • Using the CURLOPT_HTTPHEADER set the Content-Type to application/JSON.

    Example 1: This example illustrates passing the JSON Data in a URL using cURL in PHP by using the cURL POST Request.

    PHP

    Employee: Aman Job: Data Scientist Company: GeeksForGeeks id: 553 createdAt: 2022-12-02T12:32:42.420Z

    Approach for GET Request:

    • We need to specify the URL, Where the JSON data is going to be sent.
    • Using curl_init() we initialize cURL.
    • Next, we have to set options for the cURL.
    • Fetching $url using CURLOPT_URL.
    • Setting the curl option RETURNTRANSFER to true so that it returns the response instead of just outputting it.
    • Setting multiple options for a cURL session. Using the curl_setopt_array() function, setting a large number of options for cURL without repetitively calling it.
    • Using curl_exec() to execute the GET request.
    • Decode the response and Return the response as a string.
    • Close the cURL.

    Example 2: This example illustrates passing the JSON Data in a URL using cURL in PHP by using the cURL GET Request.

    PHP

    Array ( [page] => 2 [per_page] => 6 [total] => 12 [total_pages] => 2 [data] => Array ( [0] => Array ( [id] => 7 [email] => michael.lawson@reqres.in [first_name] => Michael [last_name] => Lawson [avatar] => https://reqres.in/img/faces/7-image.jpg ) [1] => Array ( [id] => 8 [email] => lindsay.ferguson@reqres.in [first_name] => Lindsay [last_name] => Ferguson [avatar] => https://reqres.in/img/faces/8-image.jpg ) [2] => Array ( [id] => 9 [email] => tobias.funke@reqres.in [first_name] => Tobias [last_name] => Funke [avatar] => https://reqres.in/img/faces/9-image.jpg ) [3] => Array ( [id] => 10 [email] => byron.fields@reqres.in [first_name] => Byron [last_name] => Fields [avatar] => https://reqres.in/img/faces/10-image.jpg ) [4] => Array ( [id] => 11 [email] => george.edwards@reqres.in [first_name] => George [last_name] => Edwards [avatar] => https://reqres.in/img/faces/11-image.jpg ) [5] =>Array ( [id] => 12 [email] => rachel.howell@reqres.in [first_name] => Rachel [last_name] => Howell [avatar] => https://reqres.in/img/faces/12-image.jpg ) ) [support] => Array ( [url] => https://reqres.in/#support-heading => To keep ReqRes free, contributions towards server costs are appreciated! ) )

    Approach for PUT Request:

    • We need to specify the URL, where the JSON data need to be sent.
    • Using curl_init(), we initialize cURL.
    • Put JSON data in a PHP array and set up JSON data.
    • And using json_encode() encode it into JSON string.
    • Setting the options for the cURL.
      • Fetching $url using CURLOPT_URL.
      • Now attach the encoded string in the post field using CURLOPT_POSTFIELDS.
      • Setting the curl option RETURNTRANSFER to true so that it returns the response instead of just outputting it.
      • Using the CURLOPT_HTTPHEADER set the Content-Type to application/JSON.

      Example 3: This example illustrates passing the JSON Data in a URL using cURL in PHP by using the cURL PUT Request.

      Источник

      Get JSON Object From URL in PHP

      Get JSON Object From URL in PHP

      1. Use the file_get_contents() Function to Get JSON Object From the URL in PHP
      2. Use curl to Get JSON Object From the URL in PHP

      This tutorial introduces how to get the JSON object from a URL in PHP.

      Use the file_get_contents() Function to Get JSON Object From the URL in PHP

      We can use file_get_contents() along with json_decode() to get the JSON object from a URL. The file_get_contents() function reads the file in a string format. We should specify the path to the file in the function or we can even give the URL in the function as the first parameter. We should enable allow_url_fopen to use the file_get_contents() function. We can enable it by setting phpini_set(«allow_url_fopen», 1) in the php.ini file. The json_decode() function converts the JSON object into PHP object. Thus, we can access the objects in JSON URL as PHP objects.

      For the demonstration, we will use a dummy JSON URL from jsonplaceholder. Create a variable $url and store the URL in it. Use the URL https://jsonplaceholder.typicode.com/posts/1 . The JSON objects of the URL are shown below. Next, create a $json variable and use the $url as an argument to the file_get_contents() function. Now, use the json_decode() function to decode JSON string to PHP object. Store the object in the $jo variable. Lastly, access the title object with $jo and print it out.

      Thus, we accessed a URL containing a JSON object from the web and converted it into PHP. In this way, we can get JSON objects from a URL in PHP.

        "userId": 1,  "id": 1,  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" > 
      php $url = 'https://jsonplaceholder.typicode.com/posts/1'; $json = file_get_contents($url); $jo = json_decode($json); echo $jo->title; ?> 
      sunt aut facere repellat provident occaecati excepturi optio reprehenderit 

      Use curl to Get JSON Object From the URL in PHP

      curl is a command-line tool that is used to send and receive data and files. It uses supported protocols like HTTP, HTTPS, FTP, etc., and sends data from or to a server. In PHP, there is a curl library that lets us make an HTTP request. We can use curl to read file contents from the web. There are various curl functions in PHP that facilitate us to send and receive data. We can use them to get JSON objects from a URL. The curl_init() function initiates the curl. We can use the curl_setopt() function to set several options like returning transfer and setting URLs. The curl_exec() function executes the operation and curl_close() closes the curl.

      We can use the same URL as in the first method to demonstrate the use of curl . Create a variable $curl and initiate the curl with the curl_init() function. Set the CURLOPT_RETURNTRANSFER option true using the curl_setopt() function. Next, set the URL using the CURLOPT_URL option. Execute the curl with curl_exec() function with $curl in the parameter and store it in $res variable. Use the curl_close() function to close the $curl variable. Next, use the json_decode() function to change the JSON object to PHP object and display the title object.

      Thus, we can get the JSON object from a URL using curl .

      php  $curl= curl_init();  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  curl_setopt($curl, CURLOPT_URL, 'https://jsonplaceholder.typicode.com/posts/1';  $res = curl_exec($curl);  curl_close($curl);  $jo = json_decode($res);  echo $jo->title; ?> 
      sunt aut facere repellat provident occaecati excepturi optio reprehenderit 

      Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

      Related Article — JSON Object

      Источник

      Get JSON from URL in PHP

      In this tutorial, I’m going to show you how to get json from url in php script. JSON has become a popular way to exchange data and web services outputs in json format. To send a HTTP request and parse JSON response from URL is fairly simple in php but newbies may find how to parse json difficult.

      Let’s see how to build a php json parser script. For this script, I’m going to access Google MAP web service via API and get latitude and longitude co-ordinates for a location. Google map api produces both json/xml output. But for this example I’m going to get the json response and show you how to parse json object to retrieve the geo-metric details.

      php-get-json-from-url

      How to Get JSON from URL in PHP

      This is the php script to read the json data from url.

      results[0]->geometry->location->lat; $lng = $json->results[0]->geometry->location->lng; echo "Latitude: " . $lat . ", Longitude: " . $lng; // output // Latitude: 40.6781784, Longitude: -73.9441579 ?>

      The above php script sends a HTTP request to Google MAP web service along with a parameter containing a physical address. The API in turn returns the geometric co-ordinates for the address as json string — which we further decode into a php object and parse it to retrieve the latitude and longitude details.

      The php function file_get_contents($url) send a http request to the provided url and returns json data.

      The function json_decode($json) decodes the provided json string and returns as a PHP object.

      As simple as that you can parse json response. That was all about getting json from url in php.

      Источник

      Читайте также:  Change size css div
Оцените статью