php get data from url
GET info from external API/URL using PHP
I have the URL http://api.minetools.eu/ping/play.desnia.net/25565 which outputs statistics of my server.
I want to get the value of online player count to display it on my website as: Online Players: online amount
4 Answers 4
1) Don’t use file_get_contents() (If you can help it)
This is because you’d need to enable fopen_wrappers to enable file_get_contents() to work on an external source. Sometimes this is closed (depending on your host; like shared hosting), so your application will break.
Generally a good alternative is curl()
2) Using curl() to perform a GET request
3) Using the response
The response comes back in a JSON object. We can use json_decode() to put this into a usable object or array.
Your server is returning a JSON string. So you should use json_decode() function to convert that into a plain PHP object. Thereafter you can access any variable of that object.
So, something like this shall help
In short, something like:
I’d also wrap the entire thing in a function or class method to keep your code tidy. A simple «almost complete» solution could look like this:
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?
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 also can use properties with dashes:
You could use PHP’s json_decode function:
file_get_contents() is not fetching the data from url,then i tried curl and it’s working fine.
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
Some time you might get 405, set the method type correctly.
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.
Get values through post method from URL
I am trying some code to get value from URL through post method and search database table for that value and get info from the database and encode it into JSON response.
I used Postman extension on Chrome and pass the values but it is not returning. Instead it is returning the else part.
Postman Screenshot
11 Answers 11
Looking at your screen shot, you have not passed body key values, instead you passed params.
Click on Body Tab and then pass key & value pair.
As per your screenshot you are sending your empid through query parameter so you need to access that as follows
also for that you need to Request Url in Postman using GET method.
else there is another option where you can send the POST data through body as row json and access it as
You have to set the Body to «x-www-form-urlencoded» and adding the variables to be posted
Or try this SO question, its already been answered
I replicated the code and db on my system to figure out the problem. I also added some lines of code before if (isset($_POST[’empid’])) < for diagnostics sake:
The application file is index.php deployed in json directory inside webroot.
When I send any request to http://localhost/json directory (either POST/GET), Apache redirects the request as a GET request to index.php (as configured in my Apache config file). I assume this is what you’re experiencing.
But when I send the request to http://localhost/json/index.php, the request is accurately received and processed.
Therefore, I would say the solution is that you need to specify the php file and also set the empid parameter as part of the body in Postman (not as part of the url).
How to get parameters from a URL string?
How can I get only the email parameter from these URLs/values?
Please note that I am not getting these strings from browser address bar.
13 Answers 13
You can use the parse_url() and parse_str() for that.
will extract the emails from urls.
Use the parse_url() and parse_str() methods. parse_url() will parse a URL string into an associative array of its parts. Since you only want a single part of the URL, you can use a shortcut to return a string value with just the part you want. Next, parse_str() will create variables for each of the parameters in the query string. I don’t like polluting the current context, so providing a second parameter puts all the variables into an associative array.
As mentioned in other answer, best solution is using
parse_url()
The parse_url() parse URL and return its components that you can get query string using query key. Then you should use parse_str() that parse query string and return values into variable.
Also you can do this work using regex.
preg_match()
You can use preg_match() to get specific value of query string from URL.
preg_replace()
Also you can use preg_replace() to do this work in one line!
I created function from @Ruel answer. You can use this:
This is working great for me using php
A much more secure answer that I’m surprised is not mentioned here yet:
So in the case of the question you can use this to get an email value from the URL get parameters:
$email = filter_input( INPUT_GET, ’email’, FILTER_SANITIZE_EMAIL );
Might as well get into the habit of grabbing variables this way.
file_get_contents
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
file_get_contents — Читает содержимое файла в строку
Описание
Использование функции file_get_contents() наиболее предпочтительно в случае необходимости получить содержимое файла целиком, поскольку для улучшения производительности функция использует технику отображения файла в память (memory mapping), если она поддерживается вашей операционной системой.
Список параметров
Имя читаемого файла.
Смещение, с которого начнётся чтение оригинального потока. Отрицательное значение смещения будет отсчитываться с конца потока.
Поиск смещения ( offset ) не поддерживается при работе с удалёнными файлами. Попытка поиска смещения на нелокальных файлах может работать при небольших смещениях, но результат будет непредсказуемым, так как функция работает на буферизованном потоке.
Максимальный размер читаемых данных. По умолчанию чтение осуществляется пока не будет достигнут конец файла. Учтите, что этот параметр применяется и к потоку с фильтрами.
Возвращаемые значения
Функция возвращает прочтённые данные или false в случае возникновения ошибки.
Ошибки
Список изменений
Примеры
Пример #1 Получить и вывести исходный код домашней страницы сайта
Пример #2 Поиск файлов в include_path
Пример #3 Чтение секции файла
Результатом выполнения данного примера будет что-то подобное:
Пример #4 Использование потоковых контекстов
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.