[PHP] XML: HTML DOM Basics
Web Development
|
PHP has built-in modules that you can use to load and parse XML files. You can also use the HTML DOM (depends on your browser) or external libraries that you have to go through extra setup for. Just to simplify the process, I'm going to be using the DOM. If you're not comfortable with it, you can look it up at http://www.w3schools.com.
One of the things that you should not do when loading XML files is to use the PHP filesystem library. Such as fopen and fread. The problem with these is that you have to do your own means of parsing the file, which could take you a lot of time and a lot of space. Instead we just want to use a library that's already done all that. It would be impractical otherwise.
To create an instance of the DOM, do variable = new DOMDocument(). We can now call its methods and do some actual execution. We can call load to load the file, and then asXML() to return the data read (tags are ignored). Note that the file is not automatically loaded. You can research this.
|
CODE:
|
Copy / Restore :: Remove Scroll Bars
|
$_dom = new DOMDocument(); $_dom->load("louis.xml"); echo $_dom->asXML();
Select what you want to copy and in doing so you will keep the formatting when pasting it.
|
|
Since the tags are ignored, it looks pretty ugly. We can format it by running a foreach loop through the file's nodes. If you're not familiar with the XML DOM, you should look it up as to avoid confusion. I will not explain it here. When we're referring to the DOM instance, it will refer to the first node unless specified otherwise. $_dom[0] is redundant. We can obtain its children by calling children().
|
CODE:
|
Copy / Restore :: Remove Scroll Bars
|
$_children = $_dom->children(); foreach ($_children as $_child) echo $_child . "<br />";
Select what you want to copy and in doing so you will keep the formatting when pasting it.
|
|
That's about it. You can mess around with it to see the different results you get.
|
CODE:
|
Copy / Restore :: Remove Scroll Bars
|
children() - returns node's children (ie, <boy /><sister />) nextSibling() - returns next node under same parent (ie, <boy /><sister /> returns
sister) prevSibling() attributes() - returns node's attributes (ie, attr="ibute")
Select what you want to copy and in doing so you will keep the formatting when pasting it.
|
|
Please login to rate coding articles.
Click here to register a free account with us.
|
|
Comments
|
| Please login to post comments. |
|
|
I also wanted to write a article about XML & PHP but i guess you covered it all :D
|
|
|
I'll write a more extensive article supporting it later.
|
|
|
Have you thought about adding the contents of: louis.xml
Nice article anyway - xml i think is very under documented around the net for php.
Kind regards,
Scott
|
|
|
 |
Categories |
 |
|
|