代码之家  ›  专栏  ›  技术社区  ›  Eli

$simpleXML->asxml()的格式输出;[重复]

  •  36
  • Eli  · 技术社区  · 17 年前

    标题几乎说明了一切。

    如果我有类似的东西(来自php站点示例):

    $xmlstr = <<<XML
    <?xml version='1.0' standalone='yes'?>
    <movies></movies>
    XML;
    
    $sxe = new SimpleXMLElement($xmlstr);
    
    $sxe->addAttribute('type', 'documentary');
    
    $movie = $sxe->addChild('movie');
    $movie->addChild('title', 'PHP2: More Parser Stories');
    $movie->addChild('plot', 'This is all about the people who make it work.');
    
    $characters = $movie->addChild('characters');
    $character  = $characters->addChild('character');
    $character->addChild('name', 'Mr. Parser');
    $character->addChild('actor', 'John Doe');
    
    $rating = $movie->addChild('rating', '5');
    $rating->addAttribute('type', 'stars');
    
    
    echo("<pre>".htmlspecialchars($sxe->asXML())."</pre>");
    
    die();
    

    最后我输出了一个长字符串,就像这样:

    <?xml version="1.0" standalone="yes"?>
    <movies type="documentary"><movie><title>PHP2: More Parser Stories</title><plot>This is all about the people who make it work.</plot><characters><character><name>Mr. Parser</name><actor>John Doe</actor></character></characters><rating type="stars">5</rating></movie></movies>
    

    对于程序使用者来说,这是很好的,但是对于调试/人工任务,有人知道如何将其转换成一个好的缩进格式吗?

    3 回复  |  直到 8 年前
        1
  •  72
  •   Mat    14 年前

    在评论中有各种各样的解决方案 PHP manual page for SimpleXMLElement . 不是很有效,但肯定很简洁,是匿名的解决方案

    $dom = dom_import_simplexml($simpleXml)->ownerDocument;
    $dom->formatOutput = true;
    echo $dom->saveXML();
    

    只要先过滤掉明显错误的内容,PHP手册页面注释通常是满足常见需求的好来源。

        2
  •  46
  •   Bidders    13 年前

    上面的内容对我不起作用,我发现它起作用了:

    $dom = new DOMDocument("1.0");
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($simpleXml->asXML());
    echo $dom->saveXML();
    
        3
  •  7
  •   naxrohan    10 年前

    找到了类似的解决方案…格式化原始XLM数据.. php SOAP 请求 __getLastRequest & __getLastResponse ,为了快速调试XML,我将它与 google-code-prettify .

    如果您想格式化敏感的XML数据,而不想在线格式化,这是一个很好的解决方案。

    下面的一些示例代码可能对其他人有所帮助:

    $dom = new DOMDocument;
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($data); //=====$data has the raw xml data...you want to format
    
    echo '<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>';
    
    echo "<br/> <pre class=\"prettyprint\" >". htmlentities($dom->saveXML())."</pre>";
    

    下面是我得到的格式化XML输出示例:

    注: 格式化的XML可用于 $dom->saveXML() 并且可以使用php文件写入直接保存到xml文件中。

    Formatted XML Output

    推荐文章