我必须从另一个xml中创建一个新的xml。我还是不知道怎么办呢

时间:2017-11-10 01:59:56

标签: php xml

我必须使用其他xml的值制作新的xml。这是xml代码。我尝试使用xpath,但后来为了显示这些值而变得混乱。谢谢你的帮助

<rss>
    <item id='1234'>
        <g:name>Gray</g:name>
        <g:description>It's a Bag</g:description>
        <g:detailed_images>
            <g:detailed_image>abcd</g:detailed_image>
            <g:detailed_image>abcde</g:detailed_image>
            <g:detailed_image>abcdef</g:detailed_image>
        </g:detailed_images>
    </item>
<rss>

新的xml格式应为:

<rss>
<item>
<name></name>
<description></description>
<detailed_images>
  <detailed_image></detailed_image>
  <detailed_image></detailed_image>
</detailed_images>
</item>
</rss>

我的不好,这是仍在进行中的php代码。我还没有真正想到这一切。我也是xml的新手。 :d

<?php 
    $document = new DOMDocument;
    $document->preserveWhiteSpace = false;           
    $document->load('xml_edit_feeds.xml');
    $xpath = new DOMXPath($document);

    $xml = new DOMDocument;
    $rss = $xml->appendChild($xml->createElement('rss'));   

    foreach ($xpath->evaluate('//item') as $item) {
        //create tag item
        $createItem = $rss->appendChild($xml->createElement('item'));

        //getting item's attribute value
        $valueID = $item->getAttribute('id');

        //create attribute
        $itemAttribute = $xml->createAttribute('id');
        $itemAttribute->value = $valueID;
        $createItem->appendChild($itemAttribute);

        $result[] = [
            'g:name' => $xpath->evaluate('string(g:name)', $item),
            'g:description' => $xpath->evaluate('string(g:description)', $item),
            'g:detailed_images' => $xpath->evaluate('string(g:detailed_images)', $item)
          ];
    }

 ?>

1 个答案:

答案 0 :(得分:1)

使用SimpleXML会更加清晰,但是当你开始使用DOM时,我会坚持使用它并根据它做出答案。

$document = new DOMDocument;
$document->preserveWhiteSpace = false;
$document->load('xml_edit_feeds.xml');
$xpath = new DOMXPath($document);

$xml = new DOMDocument;
$rss = $xml->appendChild($xml->createElement('rss'));

foreach ($xpath->query('//item') as $item) {
    //create tag item
    $createItem = $rss->appendChild($xml->createElement('item'));

    //getting item's attribute value
    $valueID = $item->getAttribute('id');

    //create attribute
    $itemAttribute = $xml->createAttribute('id');
    $itemAttribute->value = $valueID;
    $createItem->appendChild($itemAttribute);

    $description = $item->getElementsByTagName("description");
    $descriptionE = $xml->createElement("description", $description[0]->nodeValue );
    $createItem->appendChild($descriptionE);

    $dImages = $item->getElementsByTagName("detailed_image");
    $dImagesE = $xml->createElement("detailed_images");
    $createItem->appendChild($dImagesE);
    foreach ( $dImages as $image )  {
        $img = $xml->createElement("detailed_image", $image->nodeValue );
        $dImagesE->appendChild($img);

    }
}
echo $xml->saveXML();

从原始文档中提取每个数据(此处通过getElementsByTagName选取元素),然后在新文档中创建等效节点。

使用图像时,必须使用循环一次一个地添加每个图像。