I have wasted a lot of my time trying to edit and delete a specific node in an xml file by php. Now I successfully deleted that node, but when I try to edit a node it will update only the last node.
My xml file is given below:
<?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>
my code for editing this data is:
$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");
}
}
You can use the PHP extension provided by Zorba to implement your example:
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")
You can try your example live at http://www.zorba-xquery.com/html/demo#2awjZFgWFxoIi7uE2J4HgwUQUuA=
Instruction on how to install the XQuery extension with PHP are available at http://www.zorba-xquery.com/html/entry/2011/12/27/PHP_Meets_XQuery
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.