XML从数组中搜索节点并将新数据添加到新节点

时间:2011-11-29 11:56:01

标签: php xml nodes

从本教程 - 在PHPFreaks上添加节点的部分,我确实在那里发布了但没有回复,因为教程是由他们编写的。

http://www.phpfreaks...ndling-xml-data

当我使用我的xml文件时,它会创建节点,但不会插入新数据。没有页面错误。我确信我错过了一些非常简单的事情,经过几个小时的尝试,我现在会鞠躬并寻求帮助。

这是我正在使用的脚本

<?php
// isbn => pages
$page_numbers = array(
                     '1234' => '654', // insert data into catparent node
                     '5678' => '789', // insert data into catparent node
                );
$dom = new DOMDocument();
$dom->load('edtest.xml');
$xpath = new DOMXPath($dom);
$items = $xpath->query('item');
foreach($items as $item)
{
  $item->appendChild($dom->createElement('catparent', $page_numbers[$item->getAttribute('catcode')]));
}
$dom->save('edtest_new.xml');
?>

我的XML

<?xml version="1.0" encoding="UTF-8"?>
<items>
<item>
<catcode>1234</catcode>
<catdesc>Systems - System Bundles</catdesc>
<price_cost>999.95</price_cost>
<price_sell>999.95</price_sell>
</item>
</items>

输出XML

<?xml version="1.0" encoding="UTF-8"?>
<items>
<item>
<catcode>1234</catcode>
<catdesc>Systems - System Bundles</catdesc>
<price_cost>999.95</price_cost>
<price_sell>999.95</price_sell>

<catparent></catparent> // it creates but does not insert required data

</item>
</items>

它运行脚本会创建所需的节点,但它不会插入所需的数据。该脚本的目标是查找<catcode> = 1234并添加一个新的<catparent> </catparent>以及数组中所需的数据。

如果有更好的方法来达到结果或只是需要修正。

谢谢

1 个答案:

答案 0 :(得分:0)

您正在使用$item->getAttribute('catcode')。但是,catcode不是<item>的属性,而是子元素。

尝试

$catcode = $item->getElementsByTagName('catcode');
$parent_code  = $page_numbers[ $catcode[0] ];

$item->appendChild( $dom->createElement('catparent', $parent_code) );
相关问题