PHP domDocument to remove child nodes of a child node

孤人 提交于 2019-12-20 03:14:44

问题


How do I remove a parent node of a child node, but keep all the children?

The XML file is this:

<?xml version='1.0'?>
<products>
<product>
<ItemId>531<ItemId>
<modelNumber>00000</modelNumber>
<categoryPath>
<category><name>Category A</name></category>
<category><name>Category B</name></category>
<category><name>Category C</name></category>
<category><name>Category D</name></category>
<category><name>Category E</name></category>
</categoryPath>
</product>
</products>

Basically, I need to remove the categoryPath node and the category node, but keep all of the name nodes inside of the product node. What I am aiming for is a document like this:

 <?xml version='1.0'?>
<products>
<product>
<ItemId>531<ItemId>
<modelNumber>00000</modelNumber>
<name>Category A</name>
<name>Category B</name>
 <name>Category C</name>
<name>Category D</name>
<name>Category E</name>
</product>
</products>

Is there PHP built in function to do this? Any pointers would be appreciated, I just do not know where to start because there are many child nodes.

Thanks


回答1:


A good approach to process XML data is to use the DOM facility.

It's quite easy once you get introduced to it. For example:

<?php

// load up your XML
$xml = new DOMDocument;
$xml->load('input.xml');

// Find all elements you want to replace. Since your data is really simple,
// you can do this without much ado. Otherwise you could read up on XPath.
// See http://www.php.net/manual/en/class.domxpath.php
$elements = $xml->getElementsByTagName('category');

// WARNING: $elements is a "live" list -- it's going to reflect the structure
// of the document even as we are modifying it! For this reason, it's
// important to write the loop in a way that makes it work correctly in the
// presence of such "live updates".
while($elements->length) {
    $category = $elements->item(0); 
    $name = $category->firstChild; // implied by the structure of your XML 

    // replace the category with just the name 
    $category->parentNode->replaceChild($name, $category); 
} 

// final result:
$result = $xml->saveXML();

See it in action.



来源:https://stackoverflow.com/questions/8409329/php-domdocument-to-remove-child-nodes-of-a-child-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!