我正在使用simplexml来更新xml文件,其中包含来自wordpress网站的数据。每当有人访问某个页面时,我都希望在嵌套结构中添加页面ID和视图计数器,如此...
<posts>
<post>
<postid>3231</postid>
<postviews>35</postviews>
</post>
<post>
<postid>7634</postid>
<postviews>1</postviews>
</post>
</posts>
我遇到的麻烦是插件发生在错误的位置 - 而且我得到以下内容......
<posts>
<post>
<postid>3231</postid>
<postviews>35</postviews>
<postid>22640</postid><postviews>1</postviews><postid>22538</postid><postviews>1</postviews></post>
</posts>
如您所见,<postid>
和<postviews>
节点未包含在新的<post>
父节点中。任何人都可以帮助我,这让我疯了!
到目前为止,这是我的代码,用于检查帖子ID是否存在,以及是否添加一个...
//Get the wordpress postID
$postID = get_the_ID();
$postData = get_post($postID);
//echo $postID.'<br />'.$postData->post_title.'<br />'.$postData->post_date_gmt.'<br />';
// load the document
$xml = simplexml_load_file('/Applications/MAMP/htdocs/giraffetest/test.xml');
// Check to see if the post id is already in the xml file - has it already been set?
$nodeExists = $xml->xpath("//*[contains(text(), ".$postID.")]");
//Count the results
$countNodeExists = count($nodeExists);
if($countNodeExists > 0) {
echo 'ID already here';
} else {
echo 'ID not here';
$postNode = $xml->post[0];
$postNode->addChild('postid', $postID);
$postNode->addChild('postviews', 1);
}
// save the updated document
$xml->asXML('/Applications/MAMP/htdocs/giraffetest/test.xml');
非常感谢,詹姆斯
答案 0 :(得分:0)
如果你想在你的xml文档中有一个新的<post>
元素,你的代码中应该有一个addChild('post')
。像这样更改else
部分:
/* snip */
} else {
$postNode = $xml->addChild('post'); // adding a new <post> to the top level node
$postNode->addChild('postid', $postID); // adding a <postid> inside the new <post>
$postNode->addChild('postviews', 1); // adding a postviews inside the new <post>
}