使用DOM Document和SimpleXML格式化xml。 Arrgghhh

时间:2012-11-22 11:51:45

标签: php xml simplexml domdocument

  

可能重复:
  PHP simpleXML how to save the file in a formatted way?

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

我正在使用SimpleXML来获取文件并保存它,但xml的格式是在一条长行上。

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

由于

1 个答案:

答案 0 :(得分: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);