php pretty print xml
Php pretty print xml
A tiny library for pretty printing XML, inspired purely from DomDocument’s lack of ability to configure indent distance.
Install by adding to your composer.json:
To use, just give it a badly indented (but well formed) XML string:
License and Authors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
How to pretty print XML from the command line?
Is there a (unix) shell script to format XML in human-readable form?
Basically, I want it to transform the following:
. into something like this:
11 Answers 11
xmllint
This utility comes with libxml2-utils :
Perl’s XML::Twig
This command comes with XML::Twig perl module, sometimes xml-twig-tools package:
xmlstarlet
This command comes with xmlstarlet :
tidy
Check the tidy package:
Python
Python’s xml.dom.minidom can format XML (works also on legacy python2):
saxon-lint
saxon-HE
xmllint is a command line XML tool and is included in libxml2 (http://xmlsoft.org/).
Note: If you don’t have libxml2 installed you can install it by doing the following:
CentOS
Ubuntu
sudo apt-get install libxml2-utils
Cygwin
apt-cyg install libxml2
MacOS
To install this on MacOS with Homebrew just do: brew install libxml2
Also available on Git if you want the code: git clone git://git.gnome.org/libxml2
You can also use tidy, which may need to be installed first (e.g. on Ubuntu: sudo apt-get install tidy ).
For this, you would issue something like following:
Note: has many additional readability flags, but word-wrap behavior is a bit annoying to untangle (http://tidy.sourceforge.net/docs/quickref.html).
Without installing anything on macOS / most Unix.
You didn’t mention a file, so I assume you want to provide the XML string as standard input on the command line. In that case, do the following:
As Daniel Veillard has written:
Indent level is controlled by XMLLINT_INDENT environment variable which is by default 2 spaces. Example how to change indent to 4 spaces:
This took me forever to find something that works on my mac. Here’s what worked for me:
This simple(st) solution doesn’t provide indentation, but it is nevertheless much easier on the human eye. Also it allows the xml to be handled more easily by simple tools like grep, head, awk, etc.
Use sed to replace ‘
Edit:
Disclaimer: you should usually prefer installing a mature tool like xmllint to do a job like this. XML/HTML can be a horribly mutilated mess. However, there are valid situations where using existing tooling is preferable over manually installing new ones, and where it is also a safe bet the XML’s source is valid (enough). I’ve written this script for one of those cases, but they are rare, so precede with caution.
I’d like to add a pure Bash solution, as it is not ‘that’ difficult to just do it by hand, and sometimes you won’t want to install an extra tool to do the job.
Paste it in a script file, and pipe in the xml. This assumes the xml is all on one line, and there are no extra spaces anywhere. One could easily add some extra \s* to the regexes to fix that.
Is there a pretty print for PHP?
I’m fixing some PHP scripts and I’m missing ruby’s pretty printer. i.e.
will output <:one =>1>. This even works with fairly complex objects and makes digging into an unknown script much easier. Is there some way to duplicate this functionality in PHP?
31 Answers 31
This is what I use to print my arrays:
The magic comes with the pre tag.
Both print_r() and var_dump() will output visual representations of objects within PHP.
The best I found yet is this:
And if you want it more detailed:
This will print the array as a list of nested HTML lists. HTML and your browser will take care of indenting and making it legible.
Remember to set html_errors = on in php.ini to get pretty printing of var_dump() in combination with xdebug.
Best way to do this is
Example:
Result:
About the second parameter of print_r «true» from the documentation:
When this parameter is set to TRUE, print_r() will return the information rather than print it.
This is a little function I use all the time its handy if you are debugging arrays. The title parameter gives you some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn’t.
to send to syslog or eventlog for windows
I didn’t see that anyone mentioned doing a «comma true» with your print_r command, and then you CAN use it inline with html without going through all the hoops or multi-messy looking solutions provided.
a one-liner that will give you the rough equivalent of «viewing source» to see array contents:
echo nl2br(str_replace(‘ ‘, ‘ ‘, print_r($_SERVER, true)));
This function works pretty well so long as you set header(‘Content-type: text/plain’); before outputting the return string
If you want a nicer representation of any PHP variable (than just plain text), I suggest you try nice_r(); it prints out values plus relevant useful information (eg: properties and methods for objects). Disclaimer: I wrote this myself.
PHP XML how to output nice format
Here are the codes:
If I print it in the browser I don’t get nice XML structure like
And I want to be utf-8 How is this all possible to do?
7 Answers 7
You can try to do this:
You can make set these parameter right after you’ve created the DOMDocument as well:
That’s probably more concise. Output in both cases is (Demo):
Alternatively, there is the tidy extension with tidy_repair_string which can pretty print XML data as well. It’s possible to specify indentation levels with it, however tidy will never output tabs.
With a SimpleXml object, you can simply
$xml is your simplexml object
Tried all the answers but none worked. Maybe it’s because I’m appending and removing childs before saving the XML. After a lot of googling found this comment in the php documentation. I only had to reload the resulting XML to make it work.
Two different issues here:
Set the formatOutput and preserveWhiteSpace attributes to TRUE to generate formatted XML:
Many web browsers (namely Internet Explorer and Firefox) format XML when they display it. Use either the View Source feature or a regular text editor to inspect the output.
When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).
Consider the following code:
xml formatting- simple xml does not do pretty formatting (indent formatting)
i am converting php variables into XML format.
i noticed that when i just use the DOMDocument along with;
to create the XML, it formats correctly (i.e line indenting etc)
code using just DOMDocument
However if i try using simplexml with the domDocument it no longer formats correctly ;
below is a sample of the problem
the result;
you will note that it no longer formats in the desired way.
i have followed all the online tutorial examples that combine simple xml with the dom but none of them format correctly.
UPDATE
i tried many of the solution on the forumns but non seemed to work for me.
however,i have just found this solution- it does indeed work- however, its long winded. it requires me to first save the file using the simplyXML and to then reload the the saved file and NOW save it using the DocumentDom:
1 Answer 1
First of all you were successful in finding out that DOMDocument supports formatted XML while SimpleXMLElement does not. And that is totally correct.
So as you want to use SimpleXMLElement to actually create the XML document but you also want to benefit from the formatting options from DOMDocument you might want to learn about the fact that both libraries are sister-libraries that work very well with each other. You already sort of seem to know about that as you make use of simplexml_import_dom to convert a DOMNode object into it’s SimpleXMLElement object.
The SimpleXMLElement::saveXML() method will use non-formatted output while the DOMDocument::save() method will use the formatting as you set the parameters for: