PHP domDocument删除子节点的子节点 [英] PHP domDocument to remove child nodes of a child node

查看:149
本文介绍了PHP domDocument删除子节点的子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何删除子节点的父节点,但是保留所有的子节点?

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

XML文件是这样的:

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>

基本上,我需要删除categoryPath节点和类别节点,但保留所有名称节点产品节点内部。我的目标是一个这样的文件:

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>

PHP内置PHP功能吗?任何指针都将不胜感激,我只是不知道从哪里开始,因为有很多子节点。

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.

谢谢

推荐答案

处理XML数据的好方法是使用 DOM 工具。

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.

这篇关于PHP domDocument删除子节点的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆