We will use the SimpleXMLElement function to operate xml files in php. Let's take a look at the usage of SimpleXMLElement.
The SimpleXML function allows you to convert XML into objects.
This object can be processed by using a common attribute selector or array iterator, just like any other object.
Example
Xml document format
The code is as follows: |
Copy code |
<? Php Error_reporting (E_ALL ^ E_NOTICE ); $ Op = $ _ GET ['OP']; $ Op | $ op = 'list '; $ Filename = 'guestbook. XML '; If (is_file ($ filename )){ $ Gb = simplexml_load_file ($ filename ); } Else { $ Gb = new SimpleXMLElement ("<? Xml version = '1. 0' encoding = 'utf-8'?> <Guestbook> </guestbook> "); } If ($ op = 'list '){ Header ("Content-Type: text/html; charset = utf-8 "); If (is_object ($ gb )){ Echo "<table> "; Echo "<tr> <th> ID </th> <th> User </th> <th> title </th> <th> content </th> <th> time </th> <th> IP </th> </tr> "; Foreach ($ gb-> item as $ v ){ Echo "<tr> "; Echo "<td> ". htmlspecialchars ($ v-> id ). "</td> <td> ". htmlspecialchars ($ v-> user ). "</td> <td> ". htmlspecialchars ($ v-> title ). "</td> <td> ". htmlspecialchars ($ v-> content ). "</td> <td> ". date ("Y-m-d H: I", intval ($ v-> time )). "</td> <td> ". htmlspecialchars ($ v-> ip ). "</td> "; } Echo '<table> '; } Echo "<div> <a href = 'guestbook. php? Op = add'> add </a> </div> "; } Elseif ($ op = 'save '){ If (@ $ _ POST ['user']) { $ User = $ _ POST ['user']; $ Title = $ _ POST ['title']; $ Content = $ _ POST ['content']; /* $ Id = @ count ($ gb-> item ); $ Nextid = $ id + 1; */ $ Nextid = 1; Foreach ($ gb-> item as $ v ){ $ Idarr [] = (int) $ v-> id; } $ Nextid = max ($ idarr) + 1; $ Item = $ gb-> addChild ('ITEM '); $ Item-> addChild ("id", $ nextid ); $ Item-> addChild ('user', $ user ); $ Item-> addChild ('title', $ title ); $ Item-> addChild ('content', $ content ); $ Item-> addChild ('time', time ()); $ Item-> addChild ('IP', $ _ SERVER ['remote _ ADDR ']); $ Gb-> asXML ($ filename ); // Jump page, middle page Header ("Location: guestbook. php? Op = list "); Die; } } Elseif ($ op = 'ADD '){ ?> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> <Html lang = "en"> <Head> <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"> <Title> Document </title> </Head> <Body> <Form action = "guestbook. php? Op = save "method =" post "> <Div> user: <input type = "text" name = "user"> </div> <Div> title: <input type = "text" name = "title"> </div> <Div> message: <textarea name = "content" id = "" cols = "30" rows = "10"> </textarea> </div> <Div> <input type = "submit" value = "submit message"> </div> </Form> </Body> </Html> <? Php } ?> |