2

我有一个具有以下布局的 XML 文件。<postviews>当用户查看 wordpress 帖子时,id get与默认值为 1 的节点一起写入 xml 文件,如下所示……</p>

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

如何编写更新查询,以便当再次看到 wordpress 帖子时,特定帖子 id 的 postviews 值会更新为 1,因此看起来像……</p>

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

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

谢谢,詹姆斯

4

1 回答 1

1

设法自己找到答案。这是如果文件中没有帖子 id 则添加新节点的代码,如果是则将节点值更新为 1...</p>

//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);
于 2012-11-23T08:59:36.580 回答