【问题标题】:Updating a xml file in a formatted text with php simplexml tool [duplicate]使用 php simplexml 工具更新格式化文本中的 xml 文件 [重复]
【发布时间】:2013-01-11 14:23:06
【问题描述】:

可能重复:
PHP XML how to output nice format

我正在使用这个

<?php

$file = '/Applications/MAMP/htdocs/payback_service/payback_records.xml';

if (file_exists($file)) {
    $sxe = simplexml_load_file($file);  
    $movie = $sxe->addChild('record');
    $movie->addChild('lat', 'PHP2: More Parser Stories');
    $movie->addChild('lng', 'This is all about the people who make it work.');
    $movie->addChild('address', 'PHP2: More Parser Stories');
    $movie->addChild('picture_link', 'PHP2: More Parser Stories');
    $movie->addChild('message', 'PHP2: More Parser Stories');
    $sxe->asXML($file);


} else {
    exit('Failed to open '.$file);
}

我希望以格式化的形式更新 xml 的文本。

现在我得到了这个:

<record><lat>PHP2: More Parser Stories</lat><lng>This is all about the people who make it work.</lng><address>PHP2: More Parser Stories</address><picture_link>PHP2: More Parser Stories</picture_link><message>PHP2: More Parser Stories</message></record><record><lat>PHP2: More Parser Stories</lat><lng>This is all about the people who make it work.</lng><address>PHP2: More Parser Stories</address><picture_link>PHP2: More Parser Stories</picture_link><message>PHP2: More Parser Stories</message></record></root>

我需要文件是这样的:

<record>
    <lat>1.5</lat>
    <lng>-8.5</lng>
    <address>this is the address</address>
    <picture_link>this is picture link</picture_link>
    <message>this is the message</message>
</record>
<record>
    <lat>1.5</lat>
    <lng>0.248</lng>
    <address>PHP2: More Parser Stories</address>
    <picture_link>PHP2: More Parser Stories</picture_link>
    <message>PHP2: More Parser Stories</message>
</record>

【问题讨论】:

    标签: php xml xml-parsing simplexml


    【解决方案1】:

    我认为 SimpleXML 不支持格式化。但是DOMDocument class 确实:

    <?php
    
    $file = '/Applications/MAMP/htdocs/payback_service/payback_records.xml';
    
    if (file_exists($file)) {
        $sxe = simplexml_load_file($file);  
        $movie = $sxe->addChild('record');
        $movie->addChild('lat', 'PHP2: More Parser Stories');
        $movie->addChild('lng', 'This is all about the people who make it work.');
        $movie->addChild('address', 'PHP2: More Parser Stories');
        $movie->addChild('picture_link', 'PHP2: More Parser Stories');
        $movie->addChild('message', 'PHP2: More Parser Stories');
    
        $dom = new DOMDocument('1.0');
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        $dom->loadXML($sxe->asXML());
        echo $dom->saveXML();
    
    } else {
        exit('Failed to open '.$file);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多