0

可能重复:
PHP simpleXML 如何以格式化的方式保存文件?

是否可以同时使用 SimpleXML 和 DOM 文档?

我正在使用 SimpleXML 来获取文件更新并保存它,但 xml 被格式化为一行。

如何在脚本中使用 DOM Document 来格式化输出?是否必须在 SimpleXML 位完成写入文件后完成,还是可以在之前完成?

谢谢

4

1 回答 1

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);
于 2012-11-22T12:11:16.433 回答