简体   繁体   中英

how to edit specific child of xml with php

this is the child of xml that i want to edit dynamically with php

<items>
        <item xVal="SMR012" yVal="3.76" ><![CDATA[<font color = "#000000">Rating: 3.76</font>]]></item>
        <item xVal="SMR014" yVal="4.6" ><![CDATA[<font color = "#000000">Rating: 4.6</font>]]></item>
        <item xVal="SMR015" yVal="2.56" ><![CDATA[<font color = "#000000">Rating : 2.56</font>]]></item>        
    </items>

and here is the php code that get data to edit this child

$query  = "SELECT * FROM `set`";
$result = MYSQL_QUERY($query);

while ($row = mysql_fetch_array ($result))
{
$query2  = "SELECT * FROM `release` WHERE label_id = '" . $row['ID'] . "'";
$result2 = MYSQL_QUERY($query2);
while ($info = mysql_fetch_array ($result2))
{

//here i got all the data, now i need to edit xml here

}
}

how can i edit this child dynamically? (i also need to edit that XVal and yVal attributes)

thanks.

Well I dont know if this is what you want, but this will create xml rows, and after that just replace everything between item and /item with $xml

$xml = '';


while ($info = mysql_fetch_array ($result2))
{

   $xml .= '<item xVal="'.$info['xVal'].'" yVal="'.$info['yVal'].'" >'.$info['data'].'</item>';

}

to write it use:

$handle = fopen('something.xml', 'w');          
fwrite($handle, $xml);
fclose($handle);

and to check if there is an existing xVal you need to explode this item by it's child items and check with strpos

strpos($xml, 'xVal='.$info['xVal']);

if strpos returns something other than false (use === to check if it's false cause it can return 0), then you need to replace that whole row. It's a bit lenghty code.

DOMDocument and xPath would be your best option. It seems a bit complicated at first, but it is more proper than messing around with raw xml strings.

$xml = new DOMDocument();
$xml->load('test.xml');

$xPath = new DOMXPath($xml);
$result = $xPath->query("//item[@xVal='SMR014']");
$result->item(0)->nodeValue = 'New item value';
$result->item(0)->setAttribute('xVal', 'custom xVal');
echo $xml->saveXML();

This will output the following:

<?xml version="1.0"?>
<items>
        <item xVal="SMR012" yVal="3.76"><![CDATA[<font color = "#000000">Rating: 3.76</font>]]></item>
        <item xVal="custom xVal" yVal="4.6">New item value</item>
        <item xVal="SMR015" yVal="2.56"><![CDATA[<font color = "#000000">Rating : 2.56</font>]]></item>                
</items>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM