Remove a child with a specific attribute, in SimpleXML for PHP

后端 未结 17 2309
星月不相逢
星月不相逢 2020-11-22 02:50

I have several identical elements with different attributes that I\'m accessing with SimpleXML:


    
    

        
17条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 03:13

    Since I encountered the same fatal error as Gerry and I'm not familiar with DOM, I decided to do it like this:

    $item = $xml->xpath("//seg[@id='A12']");
    $page = $xml->xpath("/data");
    $id = "A12";
    
    if (  count($item)  &&  count($page) ) {
        $item = $item[0];
        $page = $page[0];
    
         // find the numerical index within ->children().
        $ch = $page->children();
        $ch_as_array = (array) $ch;
    
        if (  count($ch_as_array)  &&  isset($ch_as_array['seg'])  ) {
            $ch_as_array = $ch_as_array['seg'];
            $index_in_array = array_search($item, $ch_as_array);
            if (  ($index_in_array !== false)
              &&  ($index_in_array !== null)
              &&  isset($ch[$index_in_array])
              &&  ($ch[$index_in_array]['id'] == $id)  ) {
    
                 // delete it!
                unset($ch[$index_in_array]);
    
                echo "
    "; var_dump($xml); echo "
    "; } } // end of ( if xml object successfully converted to array ) } // end of ( valid item AND section )

提交回复
热议问题