Как отправить JSON данные POST-запросом на PHP?
User782, не за что. Я изменение вопроса сделал, прими эти изменения. Твой вопрос бестолково сформулирован.
Надим Закиров, Здравствуйте. Воспользовался вашим скриптом. Открываю php файл из корня сайта , но в ответ вот такой результат :
»
Предупреждение: file_get_contents(https://yandex.com/indexnow): не удалось открыть поток: не удалось выполнить HTTP-запрос! в /var/www/u0948833/data/www/promocoupon.ru.com/IndexNowYandex.php в строке 29
Предупреждение: Невозможно изменить информацию о заголовке — заголовки уже отправлены (вывод запущен в /var/www/u0948833/data/www/promocoupon.ru.com/IndexNowYandex.php:29) в /var/www/u0948833/data/www/promocoupon.ru.com/IndexNowYandex.php на линии 35″
Может что то я не тк делаю ?
header('Content-Type: application/json; charset=UTF-8');
$data = array( "host" => "site.com", "key" => "gdD8dkmdNLlxREi2LkhJjYOH2kyQbJqM3cBKT5fl", "keyLocation" => "https://site.com/gdD8dkmdNLlxREi2LkhJjYOH2kyQbJqM3cBKT5fl.txt", "urlList" => [ "https://site.com/1", "https://site.com/2" ] ); $ch = curl_init('https://yandex.com/indexnow'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json; charset=utf-8')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); curl_close($ch); $res = json_encode($res, JSON_UNESCAPED_UNICODE); print_r($res);
Method post json php
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
JSON PHP
Обычно JSON используется для получения данных с сервера и вывода их на веб-странице.
В этой главе мы рассмотрим как обмениваться данными JSON между клиентом и сервером на PHP.
PHP файл
В PHP есть несколько встроенных функций для работы с данными JSON.
Объекты в PHP могут конвертироваться в JSON при помощи PHP функции json_encode():
name = "John"; $myObj->age = 30; $myObj->city = "New York"; $myJSON = json_encode($myObj); echo $myJSON; ?>
Клиентский JavaScript
К PHP файлу из предыдущего примера можно обратиться по AJAX запросу, используя на стороне клиента следующий JavaScript код. Функция JSON.parse() конвертирует полученные данные в JavaScript объект:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; >>; xmlhttp.open("GET", "demo_file.php", true); xmlhttp.send();
PHP массив
Массивы в PHP также конвертируются в JSON при помощи PHP функции json_encode():
Клиентский JavaScript
К PHP массиву из предыдущего примера также можно обратиться по AJAX запросу, используя на стороне клиента следующий JavaScript код. Функция JSON.parse() конвертирует полученные данные в JavaScript массив:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj[2]; >>; xmlhttp.open("GET", "demo_file_array.php", true); xmlhttp.send();
PHP база данных
PHP — это серверный язык программирования и используется для операций, выполняемых только на стороне сервера, например, для доступа к базе данных.
Представьте, что у вас на сервере есть база данных, в которой содержится информация о товарах, покупателях и поставщиках. И вы хотите получить 10 первых записей в таблице покупателей («customers»).
Используем функцию JSON.stringify(), чтобы конвертировать JavaScript объект в JSON:
obj = < "table":"customers", "limit":10 >; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < document.getElementById("demo").innerHTML = this.responseText; >>; xmlhttp.open("GET", "json_demo_db.php?x language-php"> query("SELECT name FROM ".$obj->table." LIMIT ".$obj->limit); $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?>
- Конвертируем данные запроса в объект при помощи PHP функции json_decode().
- Обращаемся к базе данных и заполняем массив запрошенными данными.
- Добавляем массив к объекту и возвращаем объект в виде строки JSON, используя функцию json_encode().
Обход полученных данных
Теперь конвертируем данные, полученные от PHP файла, в JavaScript объект или в данном случае в JavaScript массив. Для этого используем функцию JSON.parse():
. xmlhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < myObj = JSON.parse(this.responseText); for (x in myObj) < txt += myObj[x].name + "
"; > document.getElementById("demo").innerHTML = txt; > >; .
PHP метод POST
При отправке данных на сервер лучше всего использовать метод POST.
Чтобы послать AJAX запрос, используя метод POST, следует задать нужный метод и откорректировать заголовок.
Данные, отправляемые на сервер, теперь должны быть аргументом в методе send():
obj = < "table":"customers", "limit":10 >; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < myObj = JSON.parse(this.responseText); for (x in myObj) < txt += myObj[x].name + "
"; > document.getElementById("demo").innerHTML = txt; > >; xmlhttp.open("POST", "json_demo_db_post.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x language-php"> query("SELECT name FROM ".$obj->table." LIMIT ".$obj->limit); $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?>