我浪费了大量时间尝试通过php编辑和删除xml文件中的特定节点。现在我成功删除了该节点,但是当我尝试编辑节点时,它只会更新最后一个节点。
我的xml文件如下:
<?xml version="1.0"?>
<reviews>
<product name="NokiaN9White">
<user name="testuser" id="02232012062451">
<username>test@test.com</username>
<date_post>23-02-2012</date_post>
<date_update>23-02-2012</date_update>
<review>Hello dear.</review>
</user>
<user name="testuser" id="02232012062521">
<username>test@test.com</username>
<date_post>23-02-2012</date_post>
<date_update>23-02-2012</date_update>
<review>Mrr</review>
</user>
<user name="testuser" id="02232012062523">
<username>test@test.com</username>
<date_post>23-02-2012</date_post>
<date_update>23-02-2012</date_update>
<review>adfasdf</review>
</user>
</product>
</reviews>
我编辑此数据的代码是:
$xmlDoc = new DOMDocument();
$xmlDoc->load(dirname(__FILE__)."/reviews.xml");
$products = $xmlDoc->getElementsByTagName( "product" );
foreach( $products as $product )
{
$prdoductN = $product->getAttribute( "name" );
if( $prdoductN == $product_name ){
$users = $product->getElementsByTagName( "user" );
$userR = get_userName($_SESSION['userName']);
foreach( $users as $user ){
$userName = $user->getAttribute( "name" );
$review_id = $user->getAttribute( "id" );
if( $userName == $userR && $review_id == $r_id ){
$current_date = date('d-m-Y');
$eventN = $user->getElementsByTagName("date_update");
$eventN->item(0)->nodeValue = $current_date;
$eventC = $user->getElementsByTagName("review");
$eventC->item(0)->nodeValue = $comments;
}
}
$xmlDoc->formatOutput = true;
//$xmlDoc->saveXML(); // This will return the XML as a string
$xmlDoc->save(dirname(__FILE__)."/reviews.xml");
}
}
答案 0 :(得分:0)
您可以使用Zorba提供的PHP扩展来实现您的示例:
declare namespace a = "http://www.zorba-xquery.com/annotations";
declare variable $doc := <reviews>...</reviews>;
declare %a:sequential function local:remove-user(
$doc as element(reviews), $name as xs:string, $id as xs:string
) as element(reviews)
{
delete node $doc//user[@name = $name and @id = $id];
$doc
};
local:remove-user($doc, "testuser", "02232012062523")
您可以在http://www.zorba-xquery.com/html/demo#2awjZFgWFxoIi7uE2J4HgwUQUuA=
上试用您的示例有关如何使用PHP安装XQuery扩展的说明,请访问http://www.zorba-xquery.com/html/entry/2011/12/27/PHP_Meets_XQuery