duancu4731 2013-12-04 17:06
浏览 22
已采纳

我如何用PHP解析这个XML,并用它生成新的PHP文件? [关闭]

My question is about parsing xml with php. Although I understand some basics of php, please take into account that my understanding is very limited.

This is an example of the XML structure that I’m working with:

<XML_DATA item=“Beatles”>
<People>
    <Person Firstname=“George” Lastname=“Harrison” Instrument=“Guitar”>Harrison, George</Person>
    <Person Firstname=“John” Lastname=“Lennon” Instrument=“Guitar”>Lennon, John</Person>
    <Person Firstname=“Paul” Lastname=“McCartney” Instrument=“Bass”>McCartney, Paul</Person>
    <Person Firstname=“Ringo” Lastname=“Starr” Instrument=“Drums”>Starr, Ringo</Person>
</People>
</XML_DATA>

This is what I need to do with this data:

  1. Populate each Person into a table on an index page, displaying their Firstname and Lastname.
  2. For each Person, a page would be generated. On that page, Firstname, Lastname, and Instrument would be displayed.
  3. On the table on the index page, each Person’s Firstname/Lastname would be wrapped in an anchor tag, linking to their corresponding page.

How would I go about doing this?

I appreciate your help, thank-you.

  • 写回答

1条回答 默认 最新

  • donglie9067 2013-12-04 17:24
    关注

    Here is how to parse your xml file :

        $doc = new DOMDocument('1.0', 'UTF-8');
        $doc->load('your/xml/file.xml');
        $datas = $doc->getElementsByTagName('Person');
        foreach ($datas as $data)
        {
            echo $data->getAttribute('Firstname'); //displays "George", then "John" and so on...
            echo $data->getAttribute('Lastname'); //displays "Harrison", then "Lennon" and so on...
            echo $data->getAttribute('Instrument'); // displays "Guitar", then "Guitar" and so on...
            echo $data->nodeValue //displays "Harrison, George", then "Lennon, John" and so on...
        }
    

    Now you can store the datas in an array so you can manipulate them whenever you want.

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

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)