- Convert XML to JSON without attributes using PHP?
- 3 Answers 3
- Конвертирование XML в JSON на PHP 8
- Файл index.php
- Комментарии ( 0 ):
- Convert XML to JSON in PHP
- Use the simplexml_load_string() and json_encode() Function to Convert an XML String to JSON in PHP
- Related Article — PHP XML
- Related Article — PHP JSON
- Как преобразовать xml в json или в array (PHP)?
- XML to JSON conversion in PHP SimpleXML
Convert XML to JSON without attributes using PHP?
Please help me, how can I do this? what is the best practice?
you will need to loop through $xml pulling out all the individual tags and putting it into a new variable and then json_encode() it
3 Answers 3
If the node name ( box ) doesn’t change, you could use xpath :
$xml = simplexml_load_file('test.xml'); $arr = (array) $xml -> xpath('box');
. But because each box has an id , this led to a kind of madness:
$final = array(); foreach ($arr as $box)
I was going to look for a better way, but I began seeing a floating dagger so I gave up. As is, you just need to json_encode the $final array. Godspeed.
«A simple way to convert XML to JSON! A simple way to convert XML to JSON! My kingdom for a simple way to convert XML to JSON!»
You can try accessing the elements individually, such as:
$boxes = array(); // Loop through each box element. foreach($xml->box as $box) < // Add an array with the a, b, and c children. $boxes[] = array('a' =>$box-> a, 'b' => $box->b, 'c' => $box->c); > $json = json_encode($boxes);
This will loop through each box element, pull out the a, b, and c tags into an array, and then JSON encode the array instead of the SimpleXML Object.
Basically, you’ll have to do as the other respondents suggest and format the JSON output yourself.
This gives me the JSON I’m after — pretty similar to what you want. It’s recursive, so it will work for any XML.
That might be fine for you, but if not you’d only have to modify $final_tree slightly to get the array of naked «box» objects on the top level.
function xml2json($xmlString) < $start_tree = (array) simplexml_load_string(trim($xmlString)); $final_tree = array(); loopRecursivelyForAttributes($start_tree,$final_tree); return json_encode($final_tree); >function loopRecursivelyForAttributes($start_tree,&$final_tree) < foreach ($start_tree as $key1=>$row1) < if(!array_key_exists($key1, $final_tree)) < $final_tree[$key1] = array(); >// If there is only one sub node, then there will be one less // array - ie: $row1 will be an array which has an '@attributes' key if(array_key_exists('@attributes', $row1)) < $row1 = (array) $row1; getValues($start_tree,$final_tree, $key1, $row1); >else < foreach ($row1 as $row2) < $row2 = (array) $row2; getValues($start_tree,$final_tree, $key1, $row2); >> > > function getValues($start_tree,&$final_tree, $key1, $row2) < foreach ($row2 as $key3=>$val3) < $val3 = (array) $val3; if($key3 == '@attributes') < $final_tree[$key1][] = $val3; >else < $temp_parent = array(); $temp_parent[$key3] = $val3; loopRecursivelyForAttributes($temp_parent,$final_tree[$key1][count($final_tree[$key1])-1]); >> >
Конвертирование XML в JSON на PHP 8
Доброго времени суток! В данной статье мы рассмотрим с Вами, как можно создать простой сервис, единственной задачей которого будет конвертирование xml файла в json. Сервис будет принимать ссылку на XML файл и возвращать преобразованный ответ в формате JSON. Где это может пригодиться? Например, с помощью данного простого сервиса я сделал преобразование RSS ленты, которая представляет из себя XML, в JSON формат на сервере, ответ с которого потом передавался в Android приложение и выводился пользователю в интерфейсе.
Итак, приступим к коду. Основной функционал сервиса будет находиться в файле functions.php.
// отформатированный вывод json
function util_json(mixed $value): bool|string
return json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
>
// CORS заголовки, чтобы можно было запрашивать сервис посредством fetch в браузере
function cors(): void
header(‘Access-Control-Allow-Origin: *’);
header(‘Access-Control-Allow-Methods: GET, POST’);
header(‘Access-Control-Max-Age: 1000’);
header(‘Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With’);
header(‘Content-Type: application/json’);
>
// отформатированный код ответа при ошибке
function error_response(string $message, int $code = 501): bool|string
$responseMessage = [‘code’ => $code, ‘error’ => $message];
return util_json($responseMessage);
>
/**
* Сам конвертер — центральный элемент сервиса
*
* @throws Exception
*/
function convertXml2Json(string $xmlUrl): bool|string
// пытается загрузить ресурс по ссылке и преобразовать
$element = @simplexml_load_file($xmlUrl, options: LIBXML_NOCDATA);
// если ссылка не может быть загружена или возникла какая-то другая проблема — бросаем исключение
if(!$element) throw new Exception(‘Unable to parse xml resource from ‘ . $xmlUrl);
>
// форматируем в json
return util_json($element->channel);
>
// обработчик запроса от клиента
function process_request(array $request_data, string $apiKey): string|bool
$response_text = »;
try // если запрос содержит ключ авторизации и он равен нашему ключу $apiKey
if($request_data[‘key’] === $apiKey)
// если в запросе передан правильный url ресурса
if(!empty($request_data[‘resource’]) && (filter_var($request_data[‘resource’], FILTER_VALIDATE_URL) !== false))
// выполняем конвертацию
$response_text = convertXml2Json($request_data[‘resource’]);
>
else
$response_text = error_response(‘Invalid url of xml resource’);
>
>
else
$response_text = error_response(‘Wrong access key’);
>
>
catch (Exception $e) $response_text = error_response($e->getMessage());
>
Файл index.php
$url = «https://news.yandex.ru/internet.rss»;
$apiKey = «API_KEY»;
// данный запроса: resource -> url, key -> key
$mockGET = [‘resource’ => $_GET[‘url’] ?: $url, ‘key’ => $_GET[‘key’]];
// отправляем заголовки
cors();
// и результат
print process_request($mockGET, $apiKey);
Протестировать на локальном ПК можно так:
php -S localhost:8080 index.php
Открываете в браузере адрес:
В результате получим JSON представление XML ресурса. Дальше этот сервис можно разместить на хостинге, например, и использовать его в других приложениях.
Создано 17.05.2022 08:42:45
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 0 ):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.
Convert XML to JSON in PHP
This article will introduce a method to convert an XML string to JSON in PHP.
Use the simplexml_load_string() and json_encode() Function to Convert an XML String to JSON in PHP
We will use two functions to convert an XML string to JSON in PHP because there is no specialized function for direct conversion. These two functions are simplexml_load_string() and json_encode() . The correct syntax to use these functions for the conversion of an XML string to JSON is as follows.
simplexml_load_string($data, $class_name, $options, $ns, $is_prefix);
The simplexml_load_string() function accepts five parameters. The details of its parameters are as follows.
This function returns the object of class SimpleXMLElement containing the data held within the XML string, or False on failure.
json_encode($value, $flags, $depth);
This function returns the JSON value. The program below shows the ways by which we can use the simplexml_load_string() and json_encode() function to convert an XML string to JSON in PHP.
php $xml_string = XML Ms. Coder Onlivia Actora Mr. Coder El ActÓr So, this language. It is like, a programming language. Or is it a scripting language? All is revealed in this thrilling horror spoof of a documentary. PHP solves all my web problems 7 5 XML; $xml = simplexml_load_string($xml_string); $json = json_encode($xml); // convert the XML string to JSON var_dump($json); ?>
string(415) ",]>,"plot":"\n So, this language. It is like, a programming language. Or is it a\n scripting language? All is revealed in this thrilling horror spoof\n of a documentary.\n ","great-lines":,"rating":["7","5"]>>"
Related Article — PHP XML
Related Article — PHP JSON
Как преобразовать xml в json или в array (PHP)?
для simplexml_load_string как я понял нужно регистрировать все пространства имен, но это оооочень большая рутина.
http://10.113.151.152:12001/tds/analytics true true http://10.113.151.152:12001/tds/device true false false false true true false false true false 2 1 1 false false false false false false false false http://10.113.151.152:12001/tds/events true true false http://10.113.151.152:12001/tds/imaging http://10.113.151.152:12001/tds/media true true true 2 http://10.113.151.152:12001/tds/ptz http://10.113.151.152:12001/tds/extension 1 1 1 1 1
XML to JSON conversion in PHP SimpleXML
You don’t want to have the » @attributes » field encoded in the JSON, however this is the standard way how PHP JSON serializes a SimpleXMLElement.
As you say you want to change that, you need to change the way how PHP JSON serializes the object. This is possible by implementing JsonSerializable with a SimpleXMLElement on your own and then provide the JSON serialization as you wish:
class JsonSerializer extends SimpleXmlElement implements JsonSerializable < /** * SimpleXMLElement JSON serialization * * @return null|string * * @link http://php.net/JsonSerializable.jsonSerialize * @see JsonSerializable::jsonSerialize */ function jsonSerialize() < // jishan's SimpleXMLElement JSON serialization . return $serialized; >>
E.g. by using the attributes as fields like all the child elements.
You can then just integrate it easily, e.g. instead of
$xml = simplexml_load_string($result);
$xml = simplexml_load_string($result, 'JsonSerializer');
$xml = new JsonSerializer($result);
and the rest of your function works the same but just with your wishes serialization.
$result = str_replace(array("\n", "\r", "\t"), '', $data); $xml = new JsonSerializer($result); $object = new stdclass(); $object->webservice[] = $xml; $result = json_encode($object, JSON_PRETTY_PRINT); header('content-Type: application/json'); echo $result;
The serialization function for the example above is:
function jsonSerialize() < // text node (or mixed node represented as text or self closing tag) if (!count($this)) < return $this[0] == $this ? trim($this) : null ; >// process all child elements and their attributes foreach ($this as $tag => $element) < // attributes first foreach ($element->attributes() as $name => $value) < $array[$tag][$name] = $value; >// child elements second foreach($element as $name => $value) < $array[$tag][$name] = $value; >> return $array; >
- In the serialization you have to take care of the type of element your own. The differentiation is done on top for the single elements with no children. If you need attribute handling on these, you need to add it.
- The trim($this) perhaps already spares you the issue you try to catch with $result = str_replace(array(«\n», «\r», «\t»), », $data); . SimpleXMLElement in any case would JSON serialize » \r » characters (SimpleXMLElement makes use of » \n » for breaks). Additionally you might be interested in the rules of whitespace normalization in XML.
- In case an attribute has the same name as a child element, it will be overwritten by the child element.
- In case a child element that follows another child element with the same name, it will be overwritten.
The two last points are just to keep the example code simple. A way that is aligned to standard PHP JSON serialization of a SimpleXMLElement is given in a series of blog posts of mine.
Basics of exactly this procedure and an exemplary JsonSerialize implementation is available in the third post: SimpleXML and JSON Encode in PHP – Part III and End.
Another related question is: