Как получить атрибуты в выводе при конвертации из XML в JSON?

1

Проблема в том, что я конвертирую xml в json, он не отображает атрибуты, кроме одного. Вот мой код:

<?php
$url="write.xml";

$fileContents= file_get_contents($url);

    $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);

        $fileContents = trim(str_replace('"', "'", $fileContents));

        $simpleXml = simplexml_load_string($fileContents);

        $json = json_encode($simpleXml);
print $json;
?>

и вот файл write.xml:

<?xml version="1.0"?>
        <information>
          <history Placename="Rohtas_Fort">
            <wiki>Rohtas Fort is a historical garrison fort located near the city of Jhelum in Punjab, Pakistan. It was built by Raja Todar Mal, under the orders of the Afghan king Sher Shah Suri, to subdue the rebellious tribes of the northern Punjab region, in the 16th century. This fort is about 4 km in circumference</wiki>
            <year y="1555">The Rohtas fort was built to crush the local tribes of Potohar, who rebelled against the Sur dynasty after the Mughal emperor Humayun was ousted by the former.
        It took eight years to built the fort, it was captured by Mughal emperor Humayun in 1555.The Rohtas fort was built to crush the local tribes of Potohar, who rebelled against the Sur dynasty after the Mughal emperor Humayun was ousted by the former.
        It took eight years to built the fort, it was captured by Mughal emperor Humayun in 1555.</year>
            <year y="2005">In the portions that have fallen away one can still see some part of the original construction.
        The central archway of the Chandwali Gate has been rebuilt recently so that is the only &#x201C;fake&#x201D; part of the fort.
        In early 2005, seepage, heavy rains, and general neglect caused the left inner face of the Talaqi Gate to collapse, and the right flank and foundation to become detached from the original structure.
        The Gatali Gate forms one of the original entrances to Rohtas</year>
            <year y="1997">Over time, its right bastion and supporting wall have collapsed as a result of permeated rainwater and the erosion of its foundations.


        === World Heritage Site ===
        Qila Rohtas was designated a World Heritage Site in 1997...It is undertaking the following projects in conjunction with the Royal Norwegian Embassy.
        Complete restoration of Shah Chandwali Gate
        Conservation of Haveli Man Singh
        Conservation of Talaqi Gate and Gatali Gate
        Establishment of Sher Shah Suri Museum in upper storey of Sohail Gate
        Improvement of quality of life in Rohtas Fort village


        == Nearby places of historical significance ==

        Outside the Langar Khani Gate is the tomb of a lady called Khair Un Nisa.She was the daughter of the food minister named Qadir Bukhsh.She died here and was buried in this tomb but she was later moved to Sasaram.
        Until the construction of the new Grand Trunk Road, Rohtas was a halting place on the main Peshawar-Lahore road.This road had serais about a mile apart.One of these is about one mile north of the Rohtas Fort.It is in a fair state of preservation.


        == How to visit ==


        === From Islamabad ===
        The dual-carriage Grand Trunk Road takes you past Gujar Khan and Sohawa, to the small town of Dina 130 km away.Just past Dina you will drive over a railway overpass, stay to the right of the road and take the first U-turn to drive back towards Dina.After about 100 meters to your left you will find a signpost, which indicates the way towards the road leading to Rohtas Fort which is 8 km away, past the small holy village of Muftian home to the Mufti Tribe.Drive on the road to enter into the fort and keep driving till you reach the parking area.


        === From Lahore ===
        Drive on G.T road past Gujranwala, Wazirabad and the city of Jhelum.About 10 minutes drive beyond the Jhelum bridge just short of the city of Dina, you will find a signpost to the left directing you to Rohtas Fort.


        == Gallery ==</year>
            <image>http://cdn.shopify.com/s/files/1/0015/2602/products/Reggie-and-the-Full-Effect-No-Country-for-Old-Musicians-560x560_1024x1024.jpg?v=1385489227</image>
            <image>http://i.telegraph.co.uk/multimedia/archive/02537/elderly_2537613b.jpg</image>
            <image>http://thumb101.shutterstock.com/display_pic_with_logo/3391/176510147/stock-photo-full-length-portrait-of-an-old-man-with-cane-gesturing-with-hand-isolated-on-white-background-176510147.jpg</image>
            <image>https://s3.amazonaws.com/media.wbur.org/wordpress/11/files/2015/04/0423_full-house.jpg</image>
            <image y="1888">http://upload.wikimedia.org/wikipedia/commons/3/39/Poison,_a_Cheyenne_woman_almost_100_years_old,_full-length,_seated,_1888_-_NARA_-_530905.jpg</image>
            <image y="2008">http://i.dailymail.co.uk/i/pix/2008/12/27/article-1102017-02E58EE0000005DC-791_233x405.jpg</image>
            <image y="2011">http://news.fulltiltboots.com/wp-content/uploads/2011/12/november-winner2.jpg</image>
            <image y="2013">http://cdn.inquisitr.com/wp-content/uploads/2013/11/Full-House-Spinoff-Show-Coming-To-Television-665x385.jpg</image>
          </history>
        </information>

и выход:

 {"history":{"@attributes":{"Placename":"Rohtas_Fort"},"wiki":"Rohtas Fort is a historical garrison fort located near the city of Jhelum in Punjab, Pakistan. It was built by Raja Todar Mal, under the orders of the Afghan king Sher Shah Suri, to subdue the rebellious tribes of the northern Punjab region, in the 16th century. This fort is about 4 km in circumference","year":["The Rohtas fort was built to crush the local tribes of Potohar, who rebelled against the Sur dynasty after the Mughal emperor Humayun was ousted by the former.It took eight years to built the fort, it was captured by Mughal emperor Humayun in 1555.The Rohtas fort was built to crush the local tribes of Potohar, who rebelled against the Sur dynasty after the Mughal emperor Humayun was ousted by the former.It took eight years to built the fort, it was captured by Mughal emperor Humayun in 1555.","In the portions that have fallen away one can still see some part of the original construction.The central archway of the Chandwali Gate has been rebuilt recently so that is the only \u201cfake\u201d part of the fort.In early 2005, seepage, heavy rains, and general neglect caused the left inner face of the Talaqi Gate to collapse, and the right flank and foundation to become detached from the original structure.The Gatali Gate forms one of the original entrances to Rohtas","Over time, its right bastion and supporting wall have collapsed as a result of permeated rainwater and the erosion of its foundations.=== World Heritage Site ===Qila Rohtas was designated a World Heritage Site in 1997...It is undertaking the following projects in conjunction with the Royal Norwegian Embassy.Complete restoration of Shah Chandwali GateConservation of Haveli Man SinghConservation of Talaqi Gate and Gatali GateEstablishment of Sher Shah Suri Museum in upper storey of Sohail GateImprovement of quality of life in Rohtas Fort village== Nearby places of historical significance ==Outside the Langar Khani Gate is the tomb of a lady called Khair Un Nisa.She was the daughter of the food minister named Qadir Bukhsh.She died here and was buried in this tomb but she was later moved to Sasaram.Until the construction of the new Grand Trunk Road, Rohtas was a halting place on the main Peshawar-Lahore road.This road had serais about a mile apart.One of these is about one mile north of the Rohtas Fort.It is in a fair state of preservation.== How to visit ===== From Islamabad ===The dual-carriage Grand Trunk Road takes you past Gujar Khan and Sohawa, to the small town of Dina 130 km away.Just past Dina you will drive over a railway overpass, stay to the right of the road and take the first U-turn to drive back towards Dina.After about 100 meters to your left you will find a signpost, which indicates the way towards the road leading to Rohtas Fort which is 8 km away, past the small holy village of Muftian home to the Mufti Tribe.Drive on the road to enter into the fort and keep driving till you reach the parking area.=== From Lahore ===Drive on G.T road past Gujranwala, Wazirabad and the city of Jhelum.About 10 minutes drive beyond the Jhelum bridge just short of the city of Dina, you will find a signpost to the left directing you to Rohtas Fort.== Gallery =="],"image":["http:\/\/cdn.shopify.com\/s\/files\/1\/0015\/2602\/products\/Reggie-and-the-Full-Effect-No-Country-for-Old-Musicians-560x560_1024x1024.jpg?v=1385489227","http:\/\/i.telegraph.co.uk\/multimedia\/archive\/02537\/elderly_2537613b.jpg","http:\/\/thumb101.shutterstock.com\/display_pic_with_logo\/3391\/176510147\/stock-photo-full-length-portrait-of-an-old-man-with-cane-gesturing-with-hand-isolated-on-white-background-176510147.jpg","https:\/\/s3.amazonaws.com\/media.wbur.org\/wordpress\/11\/files\/2015\/04\/0423_full-house.jpg","http:\/\/upload.wikimedia.org\/wikipedia\/commons\/3\/39\/Poison,_a_Cheyenne_woman_almost_100_years_old,_full-length,_seated,_1888_-_NARA_-_530905.jpg","http:\/\/i.dailymail.co.uk\/i\/pix\/2008\/12\/27\/article-1102017-02E58EE0000005DC-791_233x405.jpg","http:\/\/news.fulltiltboots.com\/wp-content\/uploads\/2011\/12\/november-winner2.jpg","http:\/\/cdn.inquisitr.com\/wp-content\/uploads\/2013\/11\/Full-House-Spinoff-Show-Coming-To-Television-665x385.jpg"]}}

Вы можете видеть, что нет атрибута "Y", который я хочу в выводе.

Теги:

1 ответ

0
Лучший ответ

Строка JSON, созданная json_encode(), вызываемая объектом SimpleXML, не будет иметь атрибутов, json не поддерживает атрибуты. Преобразуйте свой объект SimpleXML, который вы получаете из simplexml_load_string в массив, и добавьте к нему свои атрибуты, а затем используйте json_encode для этого массива.

Большая функцию для создания массива, можно найти здесь.

Вот пример codingground с вашим xml.

Пример кода xml для json с атрибутами

  • 0
    спасибо большое помощь :)
  • 0
    Можете ли вы сказать, почему мы используем $ xml = <<< EOT это? у меня есть имя файла write.xml this $ xml = <<< EOT не записывается в начале файла, и поэтому я не получаю результаты. как сделать это преобразование, если у вас есть файл "write.xml"?
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню