PHP processing XML File Instance detailed

Source: Internet
Author: User
Tags foreach fread php code php print processing instruction valid xml parser

What is the essence of XML?

What is the essence of XML?
This is our custom tag, which is based on the information description, that can reflect the logical relationship between the data and the readability and readability of the file.
Your XML file follows the various grammatical rules of the so-called "well-formed" requirements, and a fully-defined XML file should be not only "well-formed", but also a "valid" XML file that uses these custom tags.

An XML file must conform to the various provisions defined in the file type description DTD (document type definition). The DTD is actually the product of the concept of "meta tag", which describes the syntax and vocabulary of a markup language, which defines the overall structure of the file and the syntax of the file. In short, the DTD sets out the details of all the rules a parser needs to know in order to interpret a "valid" XML file.


How to write an XML file

1. The first line <?xml version= "1.0"?>
2. Must have a outermost mark
3. XML tags are not case-sensitive, you can use Chinese, the start tag is what, the end must be what
4. All XML tags must have an end
5. All attribute values must be used in quotes
6. The level should be clear
7. The same mark cannot be nested
8. can use entity &;
9. Annotation issues
<! [Cdata[]]>

How PHP handles XML files


In fact, using PHP's XML parsing function, processing an XML document is tantamount to processing a file. As long as you write a few processing functions according to your own specific needs. Understand the XML file read, then generate the XML file is not a problem. Attention is paid to the coding and writing specifications of XML files.

Here is the example in the manual, which is really a classic example,

The code is as follows Copy Code

<?php
$file = "Xmltest.xml";
Verifying the legality of a file
function Trustedfile ($file) {
Only trust the local files owned by ourselves
if (!eregi ("^ (a-z]+)://", $file)
&& Fileowner ($file) = = Getmyuid ()) {
return true;
}
return false;
}
The function that handles the start tag. Mark with special color and output display.
Note $attribs an array
function startelement ($parser, $name, $attribs =array ()) {
Print "&lt;<font color=" #0000cc "> $name </font>";
if (sizeof ($attribs)) {
while (the list ($k, $v) = each ($attribs)) {
Print "<font color=" #009900 "> $k </font>=" <font
Color= "#990000" > $v </font> "";
}
}
print "&gt;";
}
End tag processing and display
function EndElement ($parser, $name) {
Print "&lt;/<font color=" #0000cc "> $name </font>&gt;";
}
Working with Data parts
function Characterdata ($parser, $data) {
Print "<b> $data </b>";
}
Processing instruction (PI) processor parameter processing function
function Pihandler ($parser, $target, $data) {
Switch (Strtolower ($target)) {
Case "PHP":
Global $parser _file;
If the parsed document is ' trusted ', we say it is safe
To execute PHP code inside it. If not, display the code
instead.
if (Trustedfile ($parser _file[$parser])) {
eval ($data);
} else {
printf ("Untrusted PHP Code: <i>%s</i>",
Htmlspecialchars ($data));
}
Break
}
}
Default handle handle
function DefaultHandler ($parser, $data) {
if (substr ($data, 0, 1) = = "&" && substr ($data,-1, 1) = = ";") {//Judge whether the data is an external entity, pay attention to this method of judgment.
printf (' <font color= "#aa00aa" >%s</font> ",
Htmlspecialchars ($data));
} else {
printf (' <font size= "-1" >%s</font> ",
Htmlspecialchars ($data));
}
}
External entity handle handle
function Externalentityrefhandler ($parser, $openEntityNames, $base, $systemId, $publicId) {
if ($systemId) {
if (!list ($parser, $fp) = New_xml_parser ($systemId)) {
printf ("Could not open entity%s at%SN", $openEntityNames,
$SYSTEMID);
return false;
}
while ($data = Fread ($fp, 4096)) {
if (!xml_parse ($parser, $data, feof ($fp)) {
printf ("XML error:%s at line%d while parsing entity%sn")
Xml_error_string (Xml_get_error_code ($parser)),
Xml_get_current_line_number ($parser), $openEntityNames);
Xml_parser_free ($parser);
return false;
}
}
Xml_parser_free ($parser);
return true;
}
return false;
}
XML parser.
function New_xml_parser ($file) {
Global $parser _file;
$xml _parser = Xml_parser_create (); Creates an XML parser that returns the action handle of the interpreter.
Xml_parser_set_option ($xml _parser, xml_option_case_folding, 1); Sets whether to use case folding, and target encoding
Xml_set_element_handler ($xml _parser, "startelement", "endelement");/set up start and end element processors, BOOL
Xml_set_character_data_handler ($xml _parser, "Characterdata");//Establish character data processor, BOOL
Xml_set_processing_instruction_handler ($xml _parser, "Pihandler");//Establish processing instruction (PI) processor
Xml_set_default_handler ($xml _parser, "DefaultHandler"); Default processor
Xml_set_external_entity_ref_handler ($xml _parser, "Externalentityrefhandler");//external entity pointing to processor

if (!) ( $fp = @fopen ($file, "R"))) {
return false;
}
if (!is_array ($parser _file)) {
Settype ($parser _file, "array");//Set file processing variable to array type
}
$parser _file[$xml _parser] = $file; ? An array that assigns the file name to the interpreter action handle as an index? (The interpreter's handle is returned as a resource record)
echo "<font color=red >parser =";
Print_r ($parser _file);
echo "<br> $xml _parser";
echo "</font>";
Return Array ($xml _parser, $fp); Handle to the interpreter's action handle and to the file to be analyzed
}
if (!) ( List ($xml _parser, $fp) = New_xml_parser ($file))) {
Die ("Could not open XML input");
}
print "<pre>";
while ($data = Fread ($fp, 4096)) {
if (!xml_parse ($xml _parser, $data, feof ($fp))) {//Here the conditional assignment is used. Performs if processing when the conditional expression expires, otherwise skips.
Die (sprintf ("XML error:%s at line%dn")
Xml_error_string (Xml_get_error_code ($xml _parser)),
Xml_get_current_line_number ($xml _parser)));
}
}
print "</pre>";
Print "Parse Completen";
Xml_parser_free ($xml _parser);
?>

Xmltest.xml file
<?xml version= "1.0" encoding= "UTF-8"?>
<!--omit the entity reference part because it is not very well understood in XML-->
<chapter>
<title>title </TITLE>
<para>
<informaltable>
<tgroup cols= "3" >
<tbody>
<row><entry>a1</entry><entry morerows= "1" >b1</entry><entry>c1</entry> </row>
<row><entry>a2</entry><entry>c2</entry></row>
<row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
</tbody>
</tgroup>
</informaltable>
</para>
<section id= "About" >
<title>about this document</title>
<para>
<!--This is a comment-->
<?php print ' hi! This is PHP version '. phpversion ();?>
</para>
</section>
</chapter>


There is also an example of processing an XML file into a PHP array.
<?php
Class Aminoacid {
var $name; AA Name
var $symbol; Three letter Symbol
var $code; One letter code
var $type; Hydrophobic, charged or neutral

function Aminoacid ($AA) {
foreach ($aa as $k => $v)
$this-> $k = $aa [$k];
}
}
function Readdatabase ($filename) {
Read the XML database of Aminoacids
$data = Implode ("", File ($filename));//First read the entire article into the array, then concatenate the array into a string and assign the value to $data.
$parser = Xml_parser_create ();
Xml_parser_set_option ($parser, xml_option_case_folding,0);//Do not use case folding
Xml_parser_set_option ($parser, xml_option_skip_white,1);
Xml_parse_into_struct ($parser, $data, $values, $tags)//parse XML data into an array that parses the XML file into two corresponding arrays.
The $tags parameter contains a pointer to the corresponding value in the $values array. The last two array parameters can be passed to the function by the pointer.
Xml_parser_free ($parser);
Loop through the structures
For specific applications (different XML files, modify the loop structure here to get a specific array.)
foreach ($tags as $key => $val) {
if ($key = = "molecule") {
$molranges = $val;
Each contiguous pair of array entries are the
Lower and upper range for each molecule definition
for ($i =0; $i < count ($molranges); $i +=2) {
$offset = $molranges [$i] + 1;
$len = $molranges [$i + 1]-$offset;
$tdb [] = Parsemol (Array_slice ($values, $offset, $len));
}
} else {
Continue
}
}
echo "<font color=red>values is:";
Print_r ($values);
echo "</font>";
Return Array ($TDB, $values);
}
function Parsemol ($mvalues) {
for ($i =0; $i < count ($mvalues); $i + +)
$mol [$mvalues [$i] ["tag"]] = $mvalues [$i] ["value"];

echo "<font color=blue> after Parsemol:";
Print_r ($mol);
echo "</font>";
return new Aminoacid ($mol);
}
$db = Readdatabase ("Moldb.xml");
echo "* * Database of aminoacid objects:n";
echo "<font color=purple> readdatabase:";
Print_r ($db [0]);
echo "</font>";

$s = Parsemol ($db [1]);

 
Vice Moldb.xml
<?xml version= "1.0" encoding= "UTF-8"
<moldb>
 & nbsp;  <molecule>
        <name>alanine</name>
        <symbol>ala</symbol>
         <code>a</code>
        <type>hydrophobic </type>
    </molecule>
    <molecule>
         <name>lysine</name>
        <symbol>lys</symbol>
        <code>k</code>
        <type>charged</type>
    </molecule
</moldb>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.