- file_get_contents throws 400 Bad Request error PHP
- 3 ответа
- Ещё вопросы
- Hiren’s Technical Blog
- Pages
- Monday, March 6, 2017
- PHP file_get_contents throws 400 Bad Request Error — Google Geocode API
- Hiren’s Technical Blog
- Pages
- Monday, March 6, 2017
- PHP file_get_contents throws 400 Bad Request Error — Google Geocode API
file_get_contents throws 400 Bad Request error PHP
Это отлично работает на моем локальном хосте, но когда я загружаю его на свой сервер, он выдает эту ошибку:
Предупреждение: file_get_contents (http://api.twitter.com/1/statuses/user_timeline/User.json) [function.file-get-contents]: не удалось открыть stream: HTTP-запрос не удался! HTTP/1.0 400 Bad Request.
Не знаете, что может быть причиной этого, может быть, настроить php на моем сервере? Спасибо заранее!
Пожалуйста, смотрите [этот вопрос стека] [1], так как он, вероятно, ответит на ваш вопрос. [1]: stackoverflow.com/questions/3710147/…
3 ответа
Возможно, вы захотите попробовать использовать curl для извлечения данных вместо file_get_contents. curl лучше поддерживает обработку ошибок:
// make request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://api.twitter.com/1/statuses/user_timeline/User.json"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); // convert response $output = json_decode($output); // handle error; error output if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) < var_dump($output); >curl_close($ch);
Это может дать вам более полное представление о том, почему вы получаете сообщение об ошибке. Общей ошибкой является ограничение скорости на вашем сервере.
Вы можете использовать file_get_contents , добавляя опцию ignore_errors , установленную в true , таким образом вы получите весь текст ответа в случае ошибки (например, HTTP/1.1 400), а не только простой false .
Если вы хотите получить доступ к заголовкам ответов, вы можете использовать $http_response_header после запроса.
Просто небольшое добавление к ответу Бена. В соответствии с руководством по PHP параметр CURLOPT_URL может быть установлен при инициализации дескриптора cURL с помощью curl_init().
// make request $ch = curl_init("http://api.twitter.com/1/statuses/user_timeline/User.json"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); // convert response $output = json_decode($output); // handle error; error output if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) < var_dump($output); >curl_close($ch);
Ещё вопросы
- 0 Как вставить элементы в массив контроллера, используя форму с полями ввода, и это будет отображаться в представлении
- 1 Как добавить ‘-‘ в YAML, используя словарь / JSON?
- 1 JMX. Можно ли сделать вложенные MBeans?
- 0 Как я могу использовать RLIKE для эффективного объединения символов LIKE и IN, * и * escape regex, где это необходимо?
- 0 Как выбрать COUNT в подзапросе оптимизированным способом
- 1 Несоответствие типов шаблонов при обновлении данных плитки
- 1 не удается скрыть бар Лебель на временной шкале Google
- 0 jquery для удаления всех элементов z-index определенного значения
- 0 Сделать элемент div растянутым на всю высоту страницы
- 0 Laravel / Omnipay PayPal, передать пользовательскую сумму доставки
- 0 PHP Oracle Pagination не может загрузить данные на следующей странице
- 1 WCF не может установить на ноутбук с помощью беспроводной
- 1 C # Crawler Перемещение однопоточного вызова WebClient в многопоточность
- 1 Дочерний элемент без корневого элемента в Java
- 0 Как получить данные результата в запросе углового обещания?
- 1 Возвратите атрибут отношения в свободном запросе Cypher
- 0 Я пытаюсь заполнить поле со списком в front-end значением поля из базы данных
- 1 Python: присвоение переменной с использованием «или» с лямбда-функциями? [Дубликат]
- 0 Как получить значение sql AS в Laravel?
- 1 Scrapy — Получение 504 тайм-аута шлюза после первых запросов
- 0 Отладка без отладочных символов
- 0 MySQL, используя сумму для столбца, чтобы получить общую сумму для каждой группы
- 1 Изменение строки в Pandas при сохранении переменной
- 1 Identity Toolkit API ранее не использовался в проекте или он отключен
- 0 Облачный сервер базы данных и физическая база данных
- 1 как заставить ckeditor перестать удалять пустые div
- 1 оператор try-catch не возвращается к блоку try при отлове исключения
- 1 Как удалить выбранные строки из фрейма данных при условии
- 1 Как программно получить имя универсального класса?
- 0 Конкатенация динамического целочисленного значения в функции php
- 0 Шрифт Google отображает поля в Internet Explorer 8 — IE 8
- 1 Unity вращает камеру с помощью сенсорного экрана — мобильный
- 1 URLDownloadToFile загрузка половины файла
- 1 Angular UrlResolver не переопределяется пользовательским провайдером
- 1 Проверка значений NaN в кадре данных pandas со столбцами int8
- 0 Невозможно получить более 15 строк в angularjs
- 1 Как сохранить несколько URL-адресов в виде файла на StartURL в Scrapy — Python?
- 0 Использование php для обработки нескольких форм на одной странице
- 0 Записать переменные JavaScript в файл JSON
- 1 Почему магическая функция ipython `% timeit -n1 code_block` выполняет` code_block` несколько раз?
- 1 удалить строку Pandas df с помощью маски на основе последней буквы столбца строки
- 0 Twig не может создать каталог кеша
- 0 Учебное пособие по Google Blobstore App Engine
- 0 PHP перенаправить с if, if else и else
- 0 Разложение LU в c ++ не работает на больших матрицах
- 0 Как получить метку времени из строки даты с часовым поясом, PHP?
- 1 Как создать несколько элементов в разных местах, используя методы DOM
- 0 HTML (PHP), связывающий файлы CSS
- 1 Как получить правильные результаты от Regex.Split с группами
- 1 Как обновить свойство навигации — без изменения каких-либо других полей
Hiren’s Technical Blog
I am a developer and I know how hard it is to solve difficult issues while programming in case you did not get any help. I have faced this so many times. That’s why I started this blog so that I can share problems and solutions with developer community. In case if you face any issue in programming do check my blog once, it will surely save your time.
Pages
Monday, March 6, 2017
PHP file_get_contents throws 400 Bad Request Error — Google Geocode API
Recently I was using Google Maps API to geocode address with PHP. There were thousands of addresses in CSV and I have to read it one by one and do geocode it and get lat long and other missing info of the address. So I was using file_get_contents function to fire HTTP request and get output like this.
$geocode = file_get_contents(‘https://maps.google.com/maps/api/geocode/json?address=’.urlencode($records[0]).’&key=API_KEY&sensor=false’);
$output = json_decode($geocode);
It worked for few address but for some addresses it throws error.
ErrorException in Controller.php line 535:
file_get_contents(URL): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
That’s because some of the addresses in the CSV were not properly formatted and there were some special characters in it as addresses were copied from web pages. But the problem was it’s eventually breaking the execution of the script. So to fix it use PHP curl instead of file_get_contents. As it does not throw exception on bad request but it gives you response code and that you can check before you get output. So here is my code.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘https://maps.google.com/maps/api/geocode/json?address=’.urlencode($records[0]).’&key=APIKEY&sensor=false’);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$geocode = curl_exec($ch);
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) // convert response
$output = json_decode($geocode);
if($output->status == ‘OK’)
>
>
curl_close($ch);
So as you can see on above code, we are using checking CURLINFO_HTTP_CODE, if it’s 200 that means HTTP request is successfully executed or in case there is a bad request you can check it and skip accessing the output. So it won’t throw an error.
Hiren’s Technical Blog
I am a developer and I know how hard it is to solve difficult issues while programming in case you did not get any help. I have faced this so many times. That’s why I started this blog so that I can share problems and solutions with developer community. In case if you face any issue in programming do check my blog once, it will surely save your time.
Pages
Monday, March 6, 2017
PHP file_get_contents throws 400 Bad Request Error — Google Geocode API
Recently I was using Google Maps API to geocode address with PHP. There were thousands of addresses in CSV and I have to read it one by one and do geocode it and get lat long and other missing info of the address. So I was using file_get_contents function to fire HTTP request and get output like this.
$geocode = file_get_contents(‘https://maps.google.com/maps/api/geocode/json?address=’.urlencode($records[0]).’&key=API_KEY&sensor=false’);
$output = json_decode($geocode);
It worked for few address but for some addresses it throws error.
ErrorException in Controller.php line 535:
file_get_contents(URL): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
That’s because some of the addresses in the CSV were not properly formatted and there were some special characters in it as addresses were copied from web pages. But the problem was it’s eventually breaking the execution of the script. So to fix it use PHP curl instead of file_get_contents. As it does not throw exception on bad request but it gives you response code and that you can check before you get output. So here is my code.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘https://maps.google.com/maps/api/geocode/json?address=’.urlencode($records[0]).’&key=APIKEY&sensor=false’);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$geocode = curl_exec($ch);
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) // convert response
$output = json_decode($geocode);
if($output->status == ‘OK’)
>
>
curl_close($ch);
So as you can see on above code, we are using checking CURLINFO_HTTP_CODE, if it’s 200 that means HTTP request is successfully executed or in case there is a bad request you can check it and skip accessing the output. So it won’t throw an error.