Php get json with curl

Базовая работа с PHP cURL: GET, POST, JSON, Headers

cURL — это программное обеспечение, которое позволяет выполнять запросы разных типов или протоколов. И как раз cURL помогает нам писать боты и парcеры на PHP, автоматизируя шаблонные HTTP-запросы, и собирая большое количество данных автоматизировано. PHP имеет встроенные инструменты по удобной работе с cURL.

PHP cURL основы

curl_init(); // инициализирует сессию работы с cURL curl_setopt(. ); // изменяет поведение cURL-сессии, в соответствии с переданными опциями curl_exec(); // выполняет cURL запрос по сконфигурированной сессии, и возвращает результат curl_close(); // закрывает сессию cURL и удаляет переменную, которой присвоен curl_init();
  • curl_init ([ string $url = NULL ] ) — с него начинается инициализация сессии cURL
  • curl_setopt ( resource $ch , int $option , mixed $value ) — конфигурирование настроек текущей сессии cURL
  • curl_exec ( resource $ch ) — выполняем запрос, получаем результат
  • curl_close ( resource $ch ) — закрытие сессии. В реальности, можно игнорировать выполнение curl_close(), так как PHP сделает это за нас, после выполнения скрипта

Отправка GET запроса из PHP cURL

Здесь всё просто, PHP cURL GET запрос — это самое простое, что можно придумать.

// URL страницы, которую открываем $url = 'https://orkhanalyshov.com'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);

В результате выполнения этого кода, переменной $response будет присвоен ответ от сервера, к которому мы стучались (в основном — это HTML или JSON).

Иногда стоит необходимость отправки GET-запроса, формируя URL-адрес из Query-параметров. Для таких случаев, можете воспользоваться встроенной PHP-функцией, формирующей URL-строку с параметрами из массива:

$queryParams = [ 'category' => 14, 'page' => 2, ]; $url = 'https://alishoff.com/?' . http_build_query($queryParams); echo $url; // https://alishoff.com/?category=14&page=2

Отправка POST запроса из PHP cURL

PHP cURL POST запрос обычно не выполняется с пустым телом. Запрос этого типа считается запросом на добавление данных (создание новой сущности в БД, к примеру) и обычно нам необходимо передавать серверу набор каких-то данных. Код отправки POST-запроса с передачей данных будет выглядеть так:

// данные POST-запроса $data = [ 'name' => 'John', 'email' => 'john@doe.com', 'body' => 'Hello, World!', 'verifyCode' => 'cugifu', ]; // url, на который отправляет данные $url = 'https://alishoff.com/contact'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response = curl_exec($ch); curl_close($ch); var_dump($response);

Отправка cURL запроса из PHP с собственными заголовками (PHP cURL Headers)

Для того, чтобы передать дополнительные, собственные заголовки, нужно с помощью функции curl_setopt() задать опцию CURLOPT_HTTPHEADER, передав массив заголовков в формате Name: Header value:

curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Custom-Header-1: The-Header-Value-1', 'Custom-Header-2: The-Header-Value-2' ]);

Отправка POST JSON запроса в PHP cURL

Читайте также:  Все команды терминала python

Очень часто, при написании ботов, имитирующих взаимодействие с API, приходится отправлять данные на целевой сервер в формате JSON. И так сложилось, что отправка Form-Data POST параметров отличается от алгоритма отправки JSON данных, потому, и передавать эти данные для cURL нужно по-другому.

Для того, чтобы корректно передать данные в формате JSON через PHP cURL, необходимо исходный массив с параметрами, перекодировать в JSON вручную, и заполнить этими данными тело (body) запроса. А так же, чтобы сервер понял, что это данные в формате JSON, нужно передать соответствующие HTTP-заголовки (о которых мы говорили выше).

$data = [ 'site' => 'https://orkhanalyshov.com', 'action' => 'notify', 'email' => 'john@doe.com', ]; $dataString = json_encode($data); $url = 'http://localhost/handler.php'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($dataString) ]); $result = curl_exec($ch); curl_close($ch);

Основной принцип передачи данных в JSON с помощью cURL заключается в том, что нужно выполнить POST запрос, тело которого заполнить закодированными в JSON данными, после чего, указать соответствующий заголовок позволяющий серверу понять, что ему на обработку пришли JSON данные.

Источник

Get JSON object from URL

I want to get JSON object from the URL and then the access_token value. So how can I retrieve it through PHP?

11 Answers 11

$json = file_get_contents('url_here'); $obj = json_decode($json); echo $obj->access_token; 

For this to work, file_get_contents requires that allow_url_fopen is enabled. This can be done at runtime by including:

You can also use curl to get the URL. To use curl, you can use the example found here:

$ch = curl_init(); // IMPORTANT: the below line is a security risk, read https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software // in most cases, you should set it to true curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, 'url_here'); $result = curl_exec($ch); curl_close($ch); $obj = json_decode($result); echo $obj->access_token; 

Sorry I forgot to mention that first how do I get this string from the url then access the json object?

The error came on this line echo $obj[‘access_token’]; Fatal error: Cannot use object of type stdClass as array in F:\wamp\www\sandbox\linkedin\test.php on line 22

@user2199343 If you want to use the result as array, use «, true» in json_decode function. See my answer for example.

Читайте также:  Python точек после запятой

you can put this line at the top ini_set(«allow_url_fopen», 1); to enable allow_url_fopen at runtime.

$url = 'http://. /. /yoururl/. '; $obj = json_decode(file_get_contents($url), true); echo $obj['access_token']; 

PHP also can use properties with dashes:

garex@ustimenko ~/src/ekapusta/deploy $ psysh Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman >>> $q = new stdClass; => <> >>> $q-> = 123 => 123 >>> var_dump($q); class stdClass#174 (1) < public $qwert-y =>int(123) > => null 

i would prefer this answer on the chosen answer for 1 reason only the parsed json could contain index with dash character ex: <"full-name":"khalil","familiy-name":"whatever">decoding as array will keep you on the safe side

You could use PHP’s json_decode function:

$url = "http://urlToYourJsonFile.com"; $json = file_get_contents($url); $json_data = json_decode($json, true); echo "My token: ". $json_data["access_token"]; 
// Get the string from the URL $json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452'); // Decode the JSON string into an object $obj = json_decode($json); // In the case of this input, do key and array lookups to get the values var_dump($obj->results[0]->formatted_address); 

Prefer code block formatting for code, and explanatory comments, especially if the code doesn’t specifically answer the question directly (in this case there are different key names etc.)

Where has this been copied from? What is the source? It looks like drive by, google the question, and blindly paste the first search result as an answer.

You need to read about the json_decode function.

$json = ''; //OR $json = file_get_contents('http://someurl.dev/. '); $obj = json_decode($json); var_dump($obj-> access_token); //OR $arr = json_decode($json, true); var_dump($arr['access_token']); 
$ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, 'url_here'); $result = curl_exec($ch); curl_close($ch); $obj = json_decode($result); echo $obj->access_token; 

Welcome to StackOverflow! This question has already been answered multiple times! Please elaborate on how your answer is different and improves the others, instead of simply dumping some code.

file_get_contents() was not fetching the data from a URL. Then I tried curl and it was working fine.

Our solution, adding some validations to response, so we are sure we have a well-formed JSON object in the $json variable:

$ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); curl_close($ch); if (! $result) < return false; >$json = json_decode(utf8_encode($result)); if (empty($json) || json_last_error() !== JSON_ERROR_NONE)

My solution only works for the following cases:

If you are mistaking a multidimensional array into a single one:

$json = file_get_contents('url_json'); // Get the JSON content $objhigher=json_decode($json); // Cconverts to an object $objlower = $objhigher[0]; // If the JSON response is multidimensional, this lowers it echo "
"; // Box for code print_r($objlower); // Prints the object with all key and values echo $objlower->access_token; // Prints the variable 
$curl_handle=curl_init(); curl_setopt($curl_handle, CURLOPT_URL,'https://www.xxxSite/get_quote/ajaxGetQuoteJSON.jsp?symbol=IRCTC&series=EQ'); //Set the GET method by giving 0 value and for POST set as 1 //curl_setopt($curl_handle, CURLOPT_POST, 0); curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); $query = curl_exec($curl_handle); $data = json_decode($query, true); curl_close($curl_handle); //print complete object, just echo the variable not work so you need to use print_r to show the result echo print_r( $data); //at first layer echo $data["tradedDate"]; //Inside the second layer echo $data["data"][0]["companyName"]; 

Some time you might get 405, set the method type correctly.

When you are using curl , it sometimes gives you a 403 (access forbidden).

I solved by adding this line to emulate a browser.

curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'); 

Источник

php: Get url content (json) with cURL

I want to access https://graph.facebook.com/19165649929?fields=name (obviously it's also accessable with "http") with cURL to get the file's content, more specific: I need the "name" (it's json). Since allow_url_fopen is disabled on my webserver, I can't use get_file_contents! So I tried it this way:

With that code I get a blank page! When I use another page, like http://www.google.com it works like a charm (I get the page's content). I guess facebook is checking something I don't know. What can it be? How can I make the code work? Thanks!

2 Answers 2

however in the thread above we found your problem beeing unable to resolve the host and this was the solution:

//$url = "https://graph.facebook.com/19165649929?fields=name"; $url = "https://66.220.146.224/19165649929?fields=name"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: graph.facebook.com')); $output = curl_exec($ch); curl_close($ch); 

Note that the Facebook Graph API requires authentication before you can view any of these pages.

You basically got two options for this. Either you login as an application (you've registered before) or as a user. See the api documentation to find out how this works.

My recommendation for you is to use the official PHP-SDK. You'll find it here. It does all the session and cURL magic for you and is very easy to use. Take the examples which are included in the package and start to experiment.

Источник

Оцените статью