复制XML属性PHP

2022-07-16 00:00:00 xml php simplexml

我需要处理XML文档,并且需要将一些字段复制到另一个XML文件。 我有此字段:

<cast>
    <person name="Nanda Anand" character="" job="Director" id="589088" thumb="" department="Directing" url="http://www.themoviedb.org/person/589088" order="0" cast_id="1000"/>
    <person name="Lynn Collins" character="" job="Actor" id="21044" thumb="http://cf2.imgobject.com/t/p/w185/berS11tKvXqTFThUWAYrH279cvn.jpg" department="Actors" url="http://www.themoviedb.org/person/21044" order="0" cast_id="1001"/>
</cast>

我需要将所有元素复制到另一个XML,但带有属性数据。 我使用此代码,但它不起作用:

foreach ($movies->movies->movie->cast->children() as $person)
            {
            $person = $cast->appendChild(
                    $xmldoc->createElement(("person"), str_replace("&", "&amp;",$person)));
            }

解决方案

如果要操作xml文档(即将节点从一个文档添加到另一个文档),则应使用DOMDocument,而不是SimpleXML。

下面是使用DOMDocument从一个文档复制到另一个文档的一些代码。请注意,这是一个两个步骤的过程。首先,将节点作为$ndTemp导入到文档中。其次,将导入的$ndTemp附加到指定的父节点(我只使用根DocentElement,但它可以是另一个节点)。

注意:如果您只是在做简单的复制,您可能想要考虑使用XSL,但这是另一回事...

输入XML(Movie.xml)

<xml>
<movie name='first'>
    <cast>
        <person name="Nanda Anand" character="" job="Director" id="589088" thumb="" department="Directing" url="http://www.themoviedb.org/person/589088" order="0" cast_id="1000"/>
        <person name="Lynn Collins" character="" job="Actor" id="21044" thumb="http://cf2.imgobject.com/t/p/w185/berS11tKvXqTFThUWAYrH279cvn.jpg" department="Actors" url="http://www.themoviedb.org/person/21044" order="0" cast_id="1001"/>
    </cast>
</movie>
<movie name='Second'>
    <cast>
        <person name="Zaphod Beeblebrox" character="" job="Director" id="589088" thumb="" department="Directing" url="http://www.themoviedb.org/person/589088" order="0" cast_id="1000"/>
    </cast>
</movie>
</xml>

PHP

<?php
    $xml = new DOMDocument();
    $strFileName = "movie.xml";
    $xml->load($strFileName);

    $xmlCopy = new DOMDocument();
    $xmlCopy->loadXML( "<xml/>" );

    $xpath = new domxpath( $xml );
    $strXPath = "/xml/movie/cast/person";

    $elements = $xpath->query( $strXPath, $xml );
    foreach( $elements as $element ) {
        $ndTemp = $xmlCopy->importNode( $element, true );
        $xmlCopy->documentElement->appendChild( $ndTemp );
    }
    echo $xmlCopy->saveXML();

?>

输出

<?xml version="1.0"?>
<xml>
    <person name="Nanda Anand" character="" job="Director" id="589088" thumb="" department="Directing" url="http://www.themoviedb.org/person/589088" order="0" cast_id="1000" />
    <person name="Lynn Collins" character="" job="Actor" id="21044" thumb="http://cf2.imgobject.com/t/p/w185/berS11tKvXqTFThUWAYrH279cvn.jpg" department="Actors"
    url="http://www.themoviedb.org/person/21044" order="0" cast_id="1001" />
    <person name="Zaphod Beeblebrox" character="" job="Director" id="589088" thumb="" department="Directing" url="http://www.themoviedb.org/person/589088" order="0" cast_id="1000" />
</xml>

相关文章