0
我正在使用simplexml来更新xml文件,其中包含来自wordpress网站的数据。每当用户访问一个网页我想要添加的页面ID和意见逆着像这样嵌套结构的文件...插入子节点时的XML问题
<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');
非常感谢,詹姆斯
非常感谢complex857! 我尝试了一些非常相似的东西,但是使用'$ xml'而不是'$ postNode' - 使用它作为变量名的原因是什么?我可以使用变量名吗?还是必须与节点名称相关? –
无论变量要求解释器的变量如何(不像人们阅读我应该添加的代码),您可以将其命名为任何您想要的内容。 – complex857