[英]XML problems with inserting child nodes
I'm using simplexml to update an xml file with data from a wordpress site. 我正在使用simplexml使用来自wordpress网站的数据更新xml文件。 Every time someone visits a page I want to add the page id and a views counter to the file in a nested structure like so…
每次有人访问页面时,我都想以类似的嵌套结构在文件中添加页面ID和视图计数器。
<posts>
<post>
<postid>3231</postid>
<postviews>35</postviews>
</post>
<post>
<postid>7634</postid>
<postviews>1</postviews>
</post>
</posts>
The trouble I'm having is that the inserts are happening at the wrong point - and i'm getting the following… 我遇到的问题是插入发生在错误的位置-我得到了以下信息…
<posts>
<post>
<postid>3231</postid>
<postviews>35</postviews>
<postid>22640</postid><postviews>1</postviews><postid>22538</postid><postviews>1</postviews></post>
</posts>
As you can see, the <postid>
and <postviews>
nodes aren't being wrapped in a new <post>
parent. 如您所见,
<postid>
和<postviews>
节点没有被包装在新的<post>
父级中。 Can anyone help me, it's driving me nuts! 谁能帮我,这让我发疯!
This is my code so far to check if the post id exists, and if not to add one… 到目前为止,这是我的代码,用于检查帖子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');
Thanks a lot, James 非常感谢,詹姆斯
If you want a new <post>
element inside your xml document you should have a addChild('post')
somewhere in your code. 如果要在xml文档中添加新的
<post>
元素,则应在代码中的某个位置添加addChild('post')
。 Change the else
part like this: 像这样更改
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>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.