Jump to content

How to make nodes indented in xml file using php?

- - - - -

  • Please log in to reply
1 reply to this topic

#1
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
Hi. I add the node and attributes to xml file, but my code fails to indent new lines of data in xml. After the addition of new data xml looks so: <setting a="1" b="aha"/><setting a="1" b="aha"/><setting a="1" b="aha"/><setting a="1" b="aha"/><setting a="1" b="aha"/><setting a="1" b="aha"/><setting a="1" b="aha"/><setting a="1" b="aha"/><setting a="1" b="aha"/></root>. Here's my code:
        public static function insertNewConfigLine($newNodeName, $attributesAndValuesArray){
            $xml = simplexml_load_file("config.xml");
            $newNode = $xml->addChild($newNodeName);
            foreach ($attributesAndValuesArray as $attribute => $value)
                $newNode->addAttribute($attribute, $value);
            file_put_contents("config.xml", $xml->asXML());
            $doc = new DOMDocument('1.0');
            $doc->preserveWhiteSpace = false;
            $doc->loadXML($xml->asXML());
            $doc->formatOutput = true;
            echo $doc->saveXML();
        }

What should i do to get proper indentation?

#2
Vaielab

Vaielab

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 547 posts
Xml was made to transfer data. And so, it was design to have the less possible amount of data to transfer. So it's normal to remove all space in it.
I don't think php have a function to add indent for xml.
I only see 2 way, either you take the xml as a string, loop throw it with a reccursive and add your indent manually, or if you are on a dedicated server you could save it to a file, and I know their some software that exist that can format a xml file, so you launch them, then read the file, and echo it content.

But both method can be pretty messy and take some time to execute.
If you want to indent if only to debug, I suggest you to open the xml with a xml software, it will indent it




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users