为了账号安全,请及时绑定邮箱和手机立即绑定

如何编辑 XML DOMDocument 的特定节点值?

如何编辑 XML DOMDocument 的特定节点值?

PHP
至尊宝的传说 2023-10-01 16:03:19
我有以下 xml 文件:<products><info><productName>Chocolate Cake</productName> <productDescription>uieovbeveb</productDescription><quantity>1</quantity><stock>22</stock><price>2.99,12.99</price><size>200 ml</size><type>India,colombia</type></info><info><productName>watermelon</productName><productDescription>fr</productDescription><quantity>rf</quantity><stock>34</stock><price>4</price><size>4</size><type>5</type></info></products>我想访问其中一个产品的 ProductDescription 标签之一并更改其值,但它不起作用。这是我到目前为止所尝试的:if (isset($_POST['editProduct'])) {$xml = new DomDocument("1.0", "UTF-8");$xml->load('./data/productDB.xml');$productName = $_POST['productName'];$productDescription = $_POST['productDescription'];$quantity = $_POST['quantity'];$stock = $_POST['stock'];$price = $_POST['price'];$size = $_POST['size'];$type = $_POST['type'];$sizetoString = implode(",", $size);$typetoString = implode(",", $type);$pricetoString = implode(",", $price);$products = $xml->getElementsByTagName('info');foreach($products as $product) {    $nameOfProduct = $product->getElementsByTagName('productName')->item(0)->nodeValue;    if($nameOfProduct == $productName) {        $product->getElementsByTagName('productDescription')->item(0)->nodeValue="";        $product->getElementByTagName('productDescription')->item(0)->appendChild($product->createTextNode($productDescription));    }}$xml->save("./data/productDB.xml");
查看完整描述

1 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

试试这个例子:


// load the document

$products = simplexml_load_file('test.xml');


// loop through each product and change description

foreach($products as $product) {

    $product->productDescription = 'new description';

}


// save the new xml

$products->asXML('test.xml');


查看完整回答
反对 回复 2023-10-01
  • 1 回答
  • 0 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信