Implementation of XML Library in PHP

Source: Internet
Author: User
Tags cdata reset xml parser

This article illustrates the XML operation class of the PHP implementation. Share to everyone for your reference, specific as follows:

This is an interface program, the need for a large number of analytical parsing xml,php xml_parse_into_struct () function can not directly generate an Easy-to-use array, and simplexml extension in PHP5 support, so browse search engine, Found a good PHP XML operation class on the Foreigner's website.

An example of usage:

1. Interpret the XML file as an Easy-to-use array:

<?php
Include (' xml.php ');//reference PHP XML action class
$xml =file_get_contents (' data.xml ');//Read XML file
$xml = file_get_contents ("Php://input"); Read the input stream that came in post
$data =xml_unserialize ($xml);
Echo ' <pre> ';
Print_r ($data);
Echo ' </pre> ';
?>

Data.xml file:

<?xmlversion= "1.0" encoding= "GBK"?>
<video>
<upload>
<videoid>998</videoid>
<name><! [Cdata[Memories of the future]]></name>
<memo><! [cdata[def]]></memo>
<up_userid>11317</up_userid>
</upload>
</video>

The corresponding array generated by the XML action Class (encoding: UTF-8):

,
Array
(
 [video] => array
   (
   [upload] => Array
     (
     [vi Deoid] => 998
     [name] => recalling the future
     [memo] => def
     [up_userid] => 11317
    )
  )
)

2. Convert an array to an XML file:

<?php
Include (' xml.php ');//reference PHP XML action class
$xml = Xml_serialize ($data);
?>

Second, the PHP XML operation class Source code:

<?php
###################################################################################
# Xml_unserialize:takes Raw Xmlasa parameter (a string)
#andreturns an equivalent PHP data structure
###################################################################################
function& xml_unserialize (& $xml) {
$xml _parser= &newxml ();
$data = & $xml _parser->parse ($xml);
$xml _parser->destruct ();
Return$data;
}
###################################################################################
# xml_serialize:serializes Any PHP data structure into XML
# takes one parameter:the data to serialize. Must be Anarray.
###################################################################################
function& xml_serialize (& $data, $level = 0, $prior _key= NULL) {
if ($level = = 0) {Ob_start (); Echo ' <?xml version= ' 1.0 '?> ', ' \ n ';}
while (the list ($key, $value) = each ($data))
if (!strpos ($key, ' attr ')) #ifit ' s not a attribute
#we don ' t treat attributes by themselves, Soforan emptyempty element
# that has attributes your still need to set the element to NULL
if (Is_array ($value) andarray_key_exists (0, $value)) {
Xml_serialize ($value, $level, $key);
}else{
$tag = $prior _key $prior _key: $key;
Echostr_repeat ("T", $level), ' < ', $tag;
if (array_key_exists ("$key attr", $data)) {#ifthere ' s an attributeforthis element
while (the list ($attr _name, $attr _value) = each ($data ["$key attr"])
Echo ', $attr _name, ' = ', Htmlspecialchars ($attr _value), ' "';
Reset ($data ["$key attr"]);
}
if (Is_null ($value)) echo "/>\n";
ElseIf (!is_array ($value)) echo ' > ', Htmlspecialchars ($value), "</$tag >\n";
Elseecho ">\n", Xml_serialize ($value, $level + 1), str_repeat ("T", $level), "</$tag >\n";
}
Reset ($data);
if ($level = = 0) {$str = &ob_get_contents (); Ob_end_clean (); return$str;}
}
###################################################################################
# Xmlclass:utilityclassto be used with PHP ' s XML handling functions
###################################################################################
classxml{
Var$parser; #a reference to the XML parser
Var$document; #the entire XML structure built up so far
Var$parent; #a pointer to the current parent-the parent would be Anarray
Var$stack; #a stack of the most recent parent at each nesting level
Var$last_opened_tag; #keeps track of the last tag opened.
Functionxml () {
$this->parser = &xml_parser_create ();
Xml_parser_set_option (& $this->parser, xml_option_case_folding, false);
Xml_set_object (& $this->parser, & $this);
Xml_set_element_handler (& $this->parser, ' open ', ' close ');
Xml_set_character_data_handler (& $this->parser, ' data ');
}
Functiondestruct () {xml_parser_free (& $this->parser);}
function& Parse (& $data) {
$this->document =array ();
$this->stack =array ();
$this->parent = & $this->document;
Returnxml_parse (& $this->parser, & $data, True)? $this->document:null;
}
Functionopen (& $parser, $tag, $attributes) {
$this->data = '; #stores Temporary CDATA
$this->last_opened_tag = $tag;
if (Is_array ($this->parent) andarray_key_exists ($tag, $this->parent)) {#ifyou ' ve seen this tag before
if (Is_array ($this->parent[$tag]) andarray_key_exists (0, $this->parent[$tag]) {#ifthe keys are numeric
#this is the Thirdorlater instance Of$tagwe ' ve come across
$key = Count_numeric_items ($this->parent[$tag]);
}else{
#this is the second instance of$tagthat we ' ve seen. Shift Around
if (array_key_exists ("$tag attr", $this->parent)) {
$arr =array (' 0 attr ' =>& $this->parent["$tag attr"], & $this->parent[$tag]);
unset ($this->parent["$tag attr"]);
}else{
$arr =array (& $this->parent[$tag]);
}
$this->parent[$tag] = & $arr;
$key = 1;
}
$this->parent = & $this->parent[$tag];
}else{
$key = $tag;
}
if ($attributes) $this->parent["$key attr"] = $attributes;
$this->parent = & $this->parent[$key];
$this->stack[] = & $this->parent;
}
Functiondata (& $parser, $data) {
if ($this->last_opened_tag!= NULL) #you don ' t need to store whitespace in between tags
$this->data. = $data;
}
Functionclose (& $parser, $tag) {
if ($this->last_opened_tag = = $tag) {
$this->parent = $this->data;
$this->last_opened_tag = NULL;
}
Array_pop ($this->stack);
if ($this->stack) $this->parent = & $this->stack[count ($this->stack)-1];
}
}
Functioncount_numeric_items (& $array) {
Returnis_array ($array) Count (Array_filter (Array_keys ($array), ' Is_numeric '): 0;
}
?>

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.