2012-11-22 22 views

回答

0
//Get the wordpress postID 
$postID = get_the_ID(); 

$postData = get_post($postID); 

// echo $postID.'<br />'.$postData->post_title.'<br />'.$postData->post_date_gmt.'<br />'; 

$xmlFile = '/Applications/MAMP/htdocs/giraffetest/test.xml'; 

// load the document 
$xml = simplexml_load_file($xmlFile); 

// Check to see if the post id is already in the xml file - has it already been set? 
$nodeExists = $xml->xpath("//post[@id=".$postID."]"); 

//Count the results 
$countNodeExists = count($nodeExists); 

if($countNodeExists > 0) { // If the ID is already in the file 

     // echo 'ID already here'; 

     // get the correct node 
     $result = $xml->xpath("//post[@id=".$postID."]/postviews"); 

     // heres the trick - the first result of xpath, and the node value (stored in [0]) 
     $result[0][0] = $result[0][0]+1; 

} else { // If the ID isn;'t there, add a new entry in the xml file for the post 

     //echo 'ID added'; 

     $postNode = $xml->addChild('post'); // adding a new <post> to the top level node 
    $postNode->addAttribute('id', $postID); // adding a <postid> inside the new <post> 
    $postNode->addChild('postviews', 1); // adding a postviews inside the new <post> 
} 

// save the updated document 

//$xml->asXML($xmlFile); 
$dom = new DOMDocument('1.0'); 
$dom->preserveWhiteSpace = false; 
$dom->formatOutput = true; 
$dom->loadXML($xml->asXML()); 
$dom->save($xmlFile); 
+0

一下[DOMDocument類](http://php.net/manual/en/class.domdocument.php) – ahiipsa

+0

嗨ahiipsa,感謝。代碼在哪裏? –

+0

不理解你 – ahiipsa