I’m using simplexml to update an xml file with data from a wordpress site. 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…
<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. 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…
//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 aaddChild('post')somewhere in your code. Change theelsepart like this: