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