【问题标题】:Format xml with DOM Document AND SimpleXML. Arrgghhh [duplicate]使用 DOM 文档和 SimpleXML 格式化 xml。啊[重复]
【发布时间】:2012-11-22 11:51:44
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

    标签: php xml simplexml domdocument


    【解决方案1】:
    //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);
    

    【讨论】:

    • 嗨 ahiipsa,谢谢。代码去哪儿了?
    • 这是我迄今为止编写的代码。您的代码需要在此文件中的哪个位置运行? - pastebin.com/QzRfBAeQ
    • 更新答案(如果我理解正确的话)
    • 还有一个额外的;在 loadXML 行中。我已将其删除,但出现以下错误... 可捕获的致命错误:传递给 DOMDocument::saveXML() 的参数 1 必须是 DOMNode 的实例,给定字符串,在 /Applications/MAMP/htdocs/giraffetest/ 中调用wp-includes/theme.php 在第 1117 行并在第 47 行的 /Applications/MAMP/htdocs/giraffetest/wp-content/themes/canvas-child/content-post.php 中定义
    猜你喜欢
    • 2013-01-11
    • 1970-01-01
    • 2011-11-10
    • 2012-04-27
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2019-04-01
    相关资源
    最近更新 更多