如何使用SimpleXML访问和覆盖XML数据?

时间:2011-11-13 18:04:52

标签: xml simplexml

我有一个XML文件:photo.xml,看起来像这样。

       <?xml version="1.0" ?> 
       - <users>
           - <uploader ID="11">
             <Name>moz</Name> 
             <Photos_Uploaded>2</Photos_Uploaded> 
           </uploader>

         </users>

因此,每次用户moz上传新照片时,XML文件都应将photos_uploaded增加1.我已经使用PHP完成了此操作。

我要问的是我如何使用SimpleXML访问photo.xml并修改数据以反映更改并保存?

问候

编辑:

我尝试了这个,但它没有用。

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


        $statistics="SELECT firstname AS 'user', count( * ) AS 'num',member_id AS ID
        FROM members
        JOIN member_photo
        USING ( member_id )
        GROUP BY firstname ";
        $result= mysql_query($statistics);


    while($row=mysql_fetch_assoc($result)) {

    $uploader=$xml->addChild('uploader');
    $uploader->addAttribute('ID',$row['ID']);
    $uploader->addChild('Name', $row['user']);
    $uploader->addChild('Photos_Uploaded', $row['num']);
    $xml->asXML('');

    }

2 个答案:

答案 0 :(得分:1)

如果我正确理解你的问题,你可以这样做:

$xml_data = '<?xml version="1.0" ?><users><uploader ID="11"><Name>moz</Name><Photos_Uploaded>2</Photos_Uploaded></uploader></users>';
$xml = simplexml_load_string($xml_data);
$xml->uploader->Photos_Uploaded = 3;
echo $xml->asXML();

此输出:

<?xml version="1.0"?><users><uploader ID="11"><Name>moz</Name><Photos_Uploaded>3</Photos_Uploaded></uploader></users>

我希望这会有所帮助:)

答案 1 :(得分:0)

截至2018年,方式是:

//load xml
$xml = simplexml_load_file('photo.xml');
// modifiy 
//your code..
// save it back
$xml->asXML('photo.xml');

来源:http://php.net/manual/en/simplexmlelement.asxml.php