使用simplexml将xml节点值更新1。可能吗?

时间:2012-11-22 10:02:21

标签: php xml simplexml xmlnode

我有一个包含以下布局的XML文件。当用户查看wordpress帖子时,id get被写入xml文件以及<postviews>节点,默认值为1,如此...

<posts>
    <post id="22640">
        <postviews>1</postviews>
    </post>
    <post id="7780">
        <postviews>1</postviews>
    </post>
</posts>

如何编写更新查询,以便在再次看到wordpress帖子时,特定帖子ID的postviews值将更新为1,因此它看起来像......

<posts>
    <post id="22640">
        <postviews>2</postviews>
    </post>
    <post id="7780">
        <postviews>1</postviews>
    </post>
</posts>

我似乎无法定位正确的节点。如何使用特定的帖子ID更新节点的子节点?

谢谢,詹姆斯

1 个答案:

答案 0 :(得分:1)

管理自己找到答案。如果post id不在文件中,那么这两个代码都会添加一个新节点,如果是...则将节点值更新为1。

//Get the wordpress postID
$postID = get_the_ID();

$postData = get_post($postID);

// echo $postID.'<br />'.$postData->post_title.'<br />'.$postData->post_date_gmt.'<br />';

$xmlFile = '/Applications/MAMP/htdocs/giraffetest/test.xml';

// load the document
$xml = simplexml_load_file($xmlFile);

// Check to see if the post id is already in the xml file - has it already been set?
$nodeExists = $xml->xpath("//post[@id=".$postID."]");

//Count the results
$countNodeExists = count($nodeExists);

if($countNodeExists > 0) { // If the ID is already in the file

    // echo 'ID already here';

    // get the correct node
    $result = $xml->xpath("//post[@id=".$postID."]/postviews");

    // heres the trick - the first result of xpath, and the node value (stored in [0])
    $result[0][0] = $result[0][0]+1; 

} else { // If the ID isn;'t there, add a new entry in the xml file for the post

    //echo 'ID added';

    $postNode = $xml->addChild('post'); // adding a new <post> to the top level node
    $postNode->addAttribute('id', $postID); // adding a <postid> inside the new <post>
    $postNode->addChild('postviews', 1); // adding a postviews inside the new <post>
}

// save the updated document
$xml->asXML($xmlFile);