dongxunhua2054 2015-05-23 14:03
浏览 154
已采纳

如何在从xml转换为json时获取输出中的属性?

The problem is when I convert xml to json, it does not show attributes except one. Here is my code:

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

$fileContents= file_get_contents($url);

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

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

        $simpleXml = simplexml_load_string($fileContents);

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

and here is write.xml file:

<?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>

and the output:

 {"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"]}}

You can see there is no attribute of 'Y', which I want in the output.

  • 写回答

1条回答 默认 最新

  • dongzhong2018 2015-05-23 14:18
    关注

    A JSON string generated by json_encode() called on a SimpleXML object will not have attributes, json does not support attributes. Convert your SimpleXML object which you get from simplexml_load_string to an array and add your attributes to it and then use json_encode on that array.

    A great function for creating the array can be found here.

    Here is a codingground example with your xml.

    codingground example xml to json with attributes

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符