Outputting XML by ID in php
I'm a complete XML newbie. I have been trying to take an XML document and display some parts of it and am having no luck displaying what I want to. Below is a simple version of my XML file:
<SOT>
<DEPARTMENT name="Aviation Technology" id="AT">
<EMPLOYEE type="Faculty">
<LOGIN>bdbowen</LOGIN>
<PASSWORD>bdbowen</PASSWORD>
<NAME>John J. Doe</NAME>
<IMAGE>images/faculty/bdbown.jpg</IMAGE>
<OFFICE>Knoy</OFFICE>
<PHONE>765.494.2884</PHONE>
<EMAIL>dsgriggs@purdue.edu</EMAIL>
</EMPLOYEE>
</DEPARTMENT>
<DEPARTMENT name="Mechanical Engineering Technology" id="MET">
<EMPLOYEE type="Faculty">
<LOGIN>bdbowen</LOGIN>
<PASSWORD>bdbowen</PASSWORD>
<NAME>John J. Doe</NAME>
<IMAGE>images/faculty/bdbown.jpg</IMAGE>
<OFFICE>Knoy</OFFICE>
<PHONE>765.494.2884</PHONE>
<EMAIL>dsgriggs@purdue.edu</EMAIL>
</EMPLOYEE>
</DEPARTMENT>
</SOT>
I want to just display the departments in a list. For example, I would like the page to print:
Aviation Technology
Mechanical Engineering Technology
Can someone please tell 开发者_如何学编程me a simple way to do this? Sorry, I'm sure this is extremely simple but I have no clue what I'm doing and am in a time crunch.
thanks for the help
Zach
First, you can always use XSLT to display whatever you want out of your XML file without using PHP at all. (just to confuse you a bit more ;) )
With PHP: What you want to do is parse the XML file and use the needed tokens, OR even better use a library that does the parsing for you and returns an object out of the XML file for you to work with easily.
SimpleXML is your friend.
$string = <<<XML
<SOT>
<DEPARTMENT name="Aviation Technology" id="AT">
<EMPLOYEE type="Faculty">
<LOGIN>bdbowen</LOGIN>
<PASSWORD>bdbowen</PASSWORD>
<NAME>John J. Doe</NAME>
<IMAGE>images/faculty/bdbown.jpg</IMAGE>
<OFFICE>Knoy</OFFICE>
<PHONE>765.494.2884</PHONE>
<EMAIL>dsgriggs@purdue.edu</EMAIL>
</EMPLOYEE>
</DEPARTMENT>
<DEPARTMENT name="Mechanical Engineering Technology" id="MET">
<EMPLOYEE type="Faculty">
<LOGIN>bdbowen</LOGIN>
<PASSWORD>bdbowen</PASSWORD>
<NAME>John J. Doe</NAME>
<IMAGE>images/faculty/bdbown.jpg</IMAGE>
<OFFICE>Knoy</OFFICE>
<PHONE>765.494.2884</PHONE>
<EMAIL>dsgriggs@purdue.edu</EMAIL>
</EMPLOYEE>
</DEPARTMENT>
</SOT>
XML;
$xml = simplexml_load_string($string);
print_r($xml);
You have all you need in that object at this point and you can display as you wish. Every element is of type SimpleXMLElement and they all implement Traversable (which means that you can use them inside of a foreach) Also if you read the docs for SimpleXMLElement, attributes(...) gives you all the attributes of an element.
精彩评论