php get json from url

Get JSON object from URL

I have a URL that returns a JSON object like this:

I want to get JSON object from the URL and then the access_token value.

So how can I retrieve it through PHP?

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

11 Answers 11

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:

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

Php also can use properties with dashes:

You could use PHP’s json_decode function:

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

file_get_contents() is not fetching the data from url,then i tried curl and it’s working fine.

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

my solution only works for the next cases: if you are mistaking a multidimensaional array into a single one

i know that the answer was has already been answered but for those who came here looking for something i hope this can help you

When you are using curl sometimes give you 403 (access forbidden) Solved by adding this line to emulate browser.

Hope this help someone.

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

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

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

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

Not the answer you’re looking for? Browse other questions tagged php json or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to use cURL to get jSON data and decode the data?

So I have a link that returns a jSON object, and I need to have it decoded and put into variables in PHP.

This is the object that it returns

I am really only interested in the

and finally the message

So how can I extract the jSON object and put it in to correct variables in PHP, that I can later use?

I just need to know how I can retrieve the jSON object, then extract the data into variables in PHP.

I am now able to get the PHP array, but I am having some troubles calling the correct values. Here is the array.

Array ( [count] => 1 [threads] => Array ( [13] => Array ( [thread_id] => 13 [node_id] => 4 [title] => Forum Integration nearly complete! [reply_count] => 0 [view_count] => 0 [user_id] => 59 [username] => Faeron [post_date] => 1369257302 [sticky] => 0 [discussion_state] => visible [discussion_open] => 1 [discussion_type] => [first_post_id] => 23 [first_post_likes] => 0 [last_post_date] => 1369257302 [last_post_id] => 23 [last_post_user_id] => 59 [last_post_username] => Faeron [prefix_id] => 1 [content] => Array ( [count] => 1 [content] => Array ( [23] => Array ( [post_id] => 23 [thread_id] => 13 [user_id] => 59 [username] => Faeron [post_date] => 1369257302 [message] => It’s been quite a while since we began to integrate the phanime Forums with the main site. We have now finished the integration with the phanime Forums and the main site. You will no longer notice that there are two platforms running phanime, but instead only one. Our next step is to theme the forums to make it look like the main site! [ip_id] => 268 [message_state] => visible [attach_count] => 0 [position] => 0 [likes] => 0 [like_users] => a:0:<> [warning_id] => 0 [warning_message] => ) ) ) ) ) )

Источник

Receive JSON POST with PHP

I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.

I get nothing when I try this:

I get nothing when I try this:

I get NULL when I try this:

The JSON format is (according to payment site documentation):

The payment site log says everything is OK. What’s the problem?

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

10 Answers 10

From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn’t in the json.

EDIT

Maybe also worth trying to echo the json string from php://input.

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

It is worth pointing out that if you use json_decode(file_get_contents(«php://input»)) (as others have mentioned), this will fail if the string is not valid JSON.

This can be simply resolved by first checking if the JSON is valid. i.e.

Edit: Note that removing strlen($json_params) above may result in subtle errors, as json_last_error() does not change when null or a blank string is passed, as shown here: http://ideone.com/va3u8U

It will give you POST data as is.

You will be able to decode it using json_decode() later.

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

This worked for me.

Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the «.PHP» file, error could be, incorrect URL.
Check whether you are calling the correct «.PHP» file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has «s» (secure) after «http».
Example:

or either way.
add or remove the «s» to match your URL.

Источник

Как отправить JSON-данные на сервер

Первый шаг на пути к облачному хранению данных.

Огромный проект у нас впереди. Скоро мы будем делать менеджер шаблонов текста, который сможет хранить наши бесценные данные не локально на компьютере, а на сервере.

Для этого мы уже сделали рабочий прототип приложения, а потом разобрались с понятием JSON. Теперь попробуем отправить данные на сервер.

Как это устроено

Если мы хотим хранить данные на сервере и отправлять их туда в любой момент, нам нужно действовать так:

Первые три пункта сделаем на клиенте — нашей HTML-странице, а скрипт и настройки — на сервере. Скрипт будем писать на PHP, поэтому, если не знаете, что это и как с этим работать, — почитайте.

Чтобы было проще, мы отправим и обработаем на сервере совсем маленький JSON — в нём всего две пары «имя: значение», но даже со сложным запросом всё будет работать так же.

Готовим HTML-страницу

У нас будет очень простая страница, потому что самое важное сейчас — научиться работать с JSON-форматом, а красоту наведём позже.

На странице нам понадобятся:

Мы сразу подключим jQuery, чтобы в скрипте напрямую обращаться к полям ввода и месту для вывода результата. А ещё заранее зададим синий цвет для вывода ответа от сервера — так мы сразу отличим данные на странице от того, что нам ответил сервер.

На языке HTML это будет так:

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from urlВнешний вид очень простой, чтобы проверить работоспособность всей системы

Отправляем данные на сервер

Обычно, чтобы отправить данные на сервер, нужно делать запрос. Вы нажимаете кнопку на странице, браузер уходит думать, ждёт ответа сервера и рисует вам новую страницу в соответствии с этим ответом. Грубо говоря, запрос на сервер заставляет вашу страницу перезагружаться.

К счастью, инженеры давно придумали, как отправлять данные на сервер, не перезагружая страницу. Для этого используют JavaScript.

// создаём новый экземпляр запроса XHR

Для запроса нам нужно знать адрес, куда будем отправлять наш JSON — это и есть адрес нашего скрипта, который мы напишем позже. Мы будем писать его на PHP, поэтому заранее можем придумать ему имя и адрес, где он будет лежать: http://mihailmaximov.ru/projects/json/json.php.

// адрес, куда мы отправим нашу JSON-строку

Когда мы знаем адрес, мы можем открыть соединение, чтобы сервер был готов принять наши данные. Это значит, что мы пока ничего ценного туда не посылаем, а просто предупреждаем сервер, что скоро что-то прилетит:

// открываем соединение. url — это переменная с нашим адресом

Теперь напишем заголовок запроса, чтобы сервер понимал, какие данные мы ему пришлём и как ему их обрабатывать. Так как у нас JSON, то это и пропишем в заголовке:

// устанавливаем заголовок —
выбираем тип контента, который отправится на сервер,
в нашем случае мы явно пишем, что это JSON

Чуть ниже сразу пропишем поведение скрипта на случай ответа сервера. Сервер должен обработать наши данные, вернуть ответ, а мы должны этот ответ поймать и вывести на страницу:

Последнее, что нам осталось сделать, — вытащить наши введённые данные из полей, собрать из них JSON и отправить на сервер:

// преобразуем наши данные JSON в строку

Пишем PHP-скрипт для сервера

Задача скрипта пока будет очень простой — ему нужно будет получить наши данные и показать, что всё пришло как нужно. В PHP уже встроена команда, которая разбирает JSON-строку на составляющие, поэтому весь скрипт будет занимать три строчки:

Сам код нам нужно сохранить как json.php и положить в папку /projects/json/ на нашем сайте — так мы прописали в скрипте на JavaScript.

Настраиваем сервер

Если мы сейчас попробуем нажать на кнопку, браузер нам выдаст ошибку:

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

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

Header set Access-Control-Allow-Origin «*»

Первая строка разрешает серверу работать с запросами от любых страниц (хоть это и небезопасно, но пока мы учимся — так можно). Вторая строка содержит список разрешённых запросов. Третья разрешает нужные нам заголовки в запросе.

Фактически этот файл сейчас означает: «разрешаю тебе принимать запросы со всех сайтов, вот такого типа запросы можно принимать, вот такие у них могут быть заголовки». В буквальном смысле методичка.

Откуда вы знаете, что нужны именно эти команды?

Когда мы писали эту статью, нам потребовалось почитать справочники и форумы, протестировать несколько вариантов команд и в итоге найти именно эту — ту, что работает.

Вся информация по командам и настройке в интернете уже есть. Нужно просто ее искать, анализировать и тестировать.

Теперь в интернете есть ещё и эта статья, которая поможет вам меньше искать 🙂

Перезапускаем нашу локальную страничку и пробуем её в действии.

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from urlВсё работает. Синий текст мы получили от PHP-скрипта на сервере. Связь налажена!

Что дальше

Мы научились отправлять данные на сервер и немного работать там с ними. Дальше попробуем заменить в наших проектах локальное хранение данных на хранение на сервере, чтобы проекты работали с любого браузера.

Источник

Returning JSON from a PHP Script

I want to return JSON from a PHP script.

Do I just echo the result? Do I have to set the Content-Type header?

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

19 Answers 19

While you’re usually fine without it, you can and should set the Content-Type header:

If I’m not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes print_r the data payload to eyeball it (though in most cases, it shouldn’t be necessary).

A complete piece of nice and clear PHP code returning JSON is:

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

php get json from url. Смотреть фото php get json from url. Смотреть картинку php get json from url. Картинка про php get json from url. Фото php get json from url

According to the manual on json_encode the method can return a non-string (false):

Returns a JSON encoded string on success or FALSE on failure.

When this happens echo json_encode($data) will output the empty string, which is invalid JSON.

json_encode will for instance fail (and return false ) if its argument contains a non UTF-8 string.

This error condition should be captured in PHP, for example like this:

Then the receiving end should of course be aware that the presence of the jsonError property indicates an error condition, which it should treat accordingly.

In production mode it might be better to send only a generic error status to the client and log the more specific error messages for later investigation.

Read more about dealing with JSON errors in PHP’s Documentation.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *