【发布时间】:2016-08-22 04:38:28
【问题描述】:
以下是我的示例 xml 数据
<?xml version="1.0"?>
<catalog>
<book>
<book NAME="ci_id">
<PVAL><![CDATA[78965]]></PVAL>
</book>
<author>testing</author>
<title>Md kaif khan</title>
<genre>kkkk</genre>
<price>5.95</price>
<publish_date>2016-09-10</publish_date>
<description>No...........</description>
</book>
<book>
<book NAME="ci_id">
<PVAL><![CDATA[78965]]></PVAL>
</book>
<author>asdfsaf</author>
<title>Md asdfsaf khan</title>
<genre>Age</genre>
<price>6.95</price>
<publish_date>2016-09-10</publish_date>
<description>Asd</description>
</book>
<book>
<book NAME="ci_id">
<PVAL><![CDATA[5210]]></PVAL>
</book>
<author>Test</author>
<title>Testing second</title>
<genre>Ttt</genre>
<price>8.94</price>
<publish_date>2013-10-15</publish_date>
<description>Nothing</description>
</book>
</catalog>
这里我的要求是添加多条记录
即,来自
<?php
$xmlFileToLoad = dirname(__FILE__) .'/testing.xml';
$xmlFileToSave = 'testing-modified.xml';
$cdata_text = '
<book>
<book NAME="ci_id">
<PVAL><![CDATA[78965]]></PVAL>
</book>
<author>testing</author>
<title>First</title>
<genre>kk</genre>
<price>5.95</price>
<publish_date>2016-09-10</publish_date>
<description>Just i am testing.</description>
</book>
<book>
<book NAME="ci_id">
<PVAL><![CDATA[78965]]></PVAL>
</book>
<author>testing1</author>
<title>Second</title>
<genre>kone</genre>
<price>5.12</price>
<publish_date>2014-10-20</publish_date>
<description>i am testing One.</description>
</book>
';
$dom = new DOMDocument();
$dom->load($xmlFileToLoad);
$xpath = new DOMXPath($dom);
function findStopPointByName($xml, $query) {
$upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZAZSCZCÓL";
$lower = "abcdefghijklmnopqrstuvwxyzazscznól";
$arg_query = "translate(text(), '$upper', '$lower')";
$q = "//book[book/PVAL[contains($arg_query, '$query')]]" ."\n";
return $xml->query($q);
}
foreach(findStopPointByName($xpath,'78965') as $node)
{
// Save parent - after removing node we will use it
$parent = $node->parentNode;
$parent->removeChild($node);
// Load XML from text. You cann't append text, only node
$data = new DOMDocument();
$data->loadXML($cdata_text);
// Import all new XML to our one and append to saved parent
$ndata = $dom->importNode($data->documentElement, true);
$parent->appendChild($ndata);
}
$dom->save($xmlFileToSave);
在上面的 $cdata_text 代码中,当我使用单个记录时(..)它是否正确添加到目标文件中。但是我需要添加两条记录(它们具有相同的 id(即 78965,实际上在我的代码中,我使用 xml 中的特定 id 进行搜索并使用 $cdata_text 进行更新,当我使用单个记录时,它正在更新,但现在我想添加多个相同 id 的记录(来自 $cdata_text)或者我可以说,我需要从 xml 文件中找到 id 并需要用 $cdata_text 字符串更新它。
请指导我。
【问题讨论】:
标签: php xml domdocument