dongningce9075 2010-01-20 10:30
浏览 56

查找特定属性中的子项的值

<data>
    <gig id="1">
    <date>December 19th</date>
    <venue>The Zanzibar</venue>
    <area>Liverpool</area>
    <telephone>Ticketline.co.uk</telephone>
    <price>£6</price>
    <time>Time TBA</time>
</gig>
<gig id="2">
    <date>Sat. 16th Jan</date>
    <venue>Celtic Connection, Classic Grand</venue>
    <area>Glasgow</area>
    <telephone>0141 353 8000</telephone>
    <price>£17.50</price>
    <time>7pm</time>
</gig>

Say if I wanted to view the values of "date" from the gig element which has an attribute of 2 how could I do this using php ?

Basically I want to delete the say id 2 and then create it again or just modify it.

using simpleXML how can I just delete a certain part ?

  • 写回答

1条回答 默认 最新

  • douhui8454 2010-01-20 10:39
    关注

    To find nodes, use XPath.

    $data->xpath('//gig[@id="2"]');
    

    It will return an array with all <gig/> nodes with an attribute id whose value is 2. Usually, it will contain 0 or 1 element. You can modify those directly. For example:

    $data = simplexml_load_string(
        '<data>
            <gig id="1">
                <date>December 19th</date>
                <venue>The Zanzibar</venue>
                <area>Liverpool</area>
                <telephone>Ticketline.co.uk</telephone>
                <price>£6</price>
                <time>Time TBA</time>
            </gig>
            <gig id="2">
                <date>Sat. 16th Jan</date>
                <venue>Celtic Connection, Classic Grand</venue>
                <area>Glasgow</area>
                <telephone>0141 353 8000</telephone>
                <price>£17.50</price>
                <time>7pm</time>
            </gig>
        </data>'
    );
    
    $nodes = $data->xpath('//gig[@id="2"]');
    
    if (empty($nodes))
    {
        // didn't find it
    }
    
    $gig = $nodes[0];
    $gig->time = '6pm';
    
    die($data->asXML());
    

    Deleting arbitrary nodes is an order of magnitude more complicated, so it's much easier to modify the values rather than deleting/recreating the node.

    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)