Home Backend Development PHP Tutorial xinputemulator PHP class for manipulating XML as a database

xinputemulator PHP class for manipulating XML as a database

Jul 29, 2016 am 08:44 AM

xml.class.php file code

Copy the code The code is as follows:


* example to read data:
*
* $xml = new xml("dbase.xml",'table');
*
* $data=$xml->xml_fetch_array();
*
* echo "

"; 
*
* print_r($data);
*
class xml
{
var $dbase; //Database, XML file to be read
var $dbname; / /Database name, top-level element, consistent with database file name
var $dbtable; //Data table, node to be obtained
var $parser; //Parser
var $vals; //Attributes
var $index; // Index
var $dbtable_array; //Node array
var $array; //Array of subordinate nodes
var $result; //Returned results
var $querys;
function xml($dbase,$dbtable)
{
$ this->dbase=$dbase;
$this->dbname=substr($dbase,strrpos($dbase,"/")+1,-4);
$this->dbtable=$dbtable;
$data=$this->ReadXml($this->dbase);
if(!$data){
die("Cannot read $this->dbname.xml");
}
$this- > ;parser,$data ,$this->vals,$this->index);
xml_parser_free($this->parser);
//Traverse the index and filter out the node name of the node to be valued: $dbtable
foreach ($this ->index as $key=>$val) {
if ($key == $this->dbtable) {
//Get the node array
$this->dbtable_array = $val;
} else {
continue;
}
}
for ($i=0; $i < count($this->dbtable_array); $i+=2) {
$offset = $this->dbtable_array[$i] + 1;
$len = $this->dbtable_array[$i + 1] - $offset;
//array_slice() returns a sequence in the array specified by the offset and length parameters.
//Get the lower-level array of the node
$value=array_slice($this->vals,$offset,$len);
//Get the valid array and merge it into the result array
$this->array[]=$ this->parseEFF($value);
}
return true;
}
//Read the XML file and return the string
function ReadXml($file)
{
return file_get_contents($file);
}
//Get an effective array
function parseEFF($effective) {
for ($i=0; $i < count($effective); $i++){
$effect[$effective[$i]["tag"] ] = $effective[$i]["value"];
}
return $effect;
}
//xml_query (method, condition, logical operator and or or for multiple conditions, array inserted or updated)
function xml_query($method,$condition,$if='and',$array=array())
{
if(($method=='select')||($method=='count')){
return $this->xml_select($method,$condition,$if);
} elseif($method=='insert') {
return $this->xml_insert($condition,$if,$array);
} elseif($method=='update') {
return $this->xml_update($condition,$if,$array);
}
}
//Get xml array
function xml_fetch_array($condition,$ if)
{
//$this->querys++;
$row = $this->array; //Initialize the data array
if($condition) {
//Whether there is a condition, if so, generate a matching Conditional array
//Generate conditional array, conditional format field, operator, match
$c//Conditional array
$cs=count($condition)/3; //Conditional number
for($i=0;$i< ;$cs;$i++){
$conditions[]=array("field"=>$condition[$i*3],"operator"=>$condition[$i*3+1],"match "=>$condition[$i*3+2]);
}
//echo count($row);
for($r=0;$r for($c=0;$c<$cs;$c++){
//$i++;
$c //Current condition
$field=$condition['field']; //Field
$operator=$ condition["operator"]; //Operator
$match=$condition['match']; //Match
if(($operator=='=')&&($row[$r][$field] ==$match)){
$true++;//If the conditions are met, the number of matches is increased by 1
} elseif(($operator=='!=')&&($row[$r][$field]!=$ match)){
$true++;//If the conditions are met, the number of matches is increased by 1
} elseif(($operator=='<')&&($row[$r][$field]<$match)) {
$true++;//If the conditions are met, the number of matches is increased by 1
} elseif(($operator=='<=')&&($row[$r][$field]<=$match)){
$true++;//If the conditions are met, add 1 to the matching number
} elseif(($operator=='>')&&($row[$r][$field]>$match)){
$true++ ;//If the conditions are met, add 1 to the matching number
} elseif(($operator=='>')&&($row[$r][$field]>=$match)){
$true++;/ /If the condition is met, add 1 to the matching number
}
}
//Get the value according to the condition
if($if=='and'){
//If the multiple conditions are and, when the matching number is equal to the condition number, generate Array
if($true==$cs){
$result[]=$row[$r];
}
} else {
//If multiple conditions are or, when there is a matching record, generate an array
if ($true!=0){
$result[]=$row[$r];
}
}
//echo $true;
//echo "
"; 
//print_r($true ; ;
//print_r($this->result);
return $result;
}
//Filtering or statistics
function xml_select($method,$condition,$if)
{
$result=$this-> ;xml_fetch_array($condition,$if);
if($method=='select'){
return $result;
} else {
return count($result);
}
}
//Insert data
function xml_insert($condition,$if,$array)
{
$data=$this->xml_fetch_array($condition,$if);//Total data array
$data[]=$array; //After insertion Total data array
$this->array=$data; //Update the total array
$this->WriteXml($data);
}
//Get the updated XML and rewrite
function xml_update($condition,$ if,$array)
{
$datas=$this->array; //Total data array
$subtract=$this->xml_fetch_array($condition,$if);//Array to be updated
// echo "
"; 
//print_r($data);
//print_r($datas);
//echo "Each record has ".count($datas[0])." values
";
for($i=0;$i$data=$datas[$i];
//echo "No. 1 in the original record." $i."item
";
foreach($data as $k=>$v){
//echo "-The ".$k." value of ".$i." item is" .$v."
";
//echo "--The value of the array ".$k." to be found is ".$subtract[0][$k]."
";
if($v==$subtract[0][$k]){
$is++;
}
}
if($is==count($data)){
//echo "----With the first ".$i." matches
";
$datas[$i]=$array;
//array_splice($datas,$i,$i+1);
}
//echo "original The ".$i." item in the record matches ".$is." to be found
";
//echo "The ".$i." item in the original record ends$is=0;
}
//array_splice($datas,2,2+1,$array);
//echo "
"; 
//print_r($datas);
$this->array=$datas;
$this->WriteXml($datas);
}
//Write XML file (write all)
function WriteXml($array)
{
if(!is_writeable($this->dbase)){
die("Unable to write".$this-> dbname.".xml");
}
$xml.="rn";
$xml.="<$this-> ;dbname>rn";
for($i=0;$i$xml.="<$this->dbtable>rn";
foreach($array [$i] as $k=>$s){
$xml.="<$k>$srn";
}
$xml.="rn";
}
$xml.="dbname>";
$fp=@fopen($this->dbase,"w");
flock($fp , LOCK_EX);
rewind($fp);
fputs($fp,$xml);
fclose($fp);
}
//Write xml line by line (I tried to write 10,000 lines, but it didn’t happen once Writing is fast, so there is no need to use this writing method)
function WriteLine($array)
{
if(!is_writeable($this->dbase)){
die("Cannot write".$this-> ;dbname.".xml");
}
$fp=@fopen($this->dbase,"w");
rewind($fp);
flock($fp, LOCK_EX);
fputs($ fp,"rn");
fputs($fp,"<$this->dbname>rn");
for($ i=0;$ifputs($fp,"<$this->dbtable>rn");
$xml.="<$this-> dbtable>rn";
foreach($array[$i] as $k=>$s){
fputs($fp,"<$k>$srn");
}
fputs($fp,"dbtable>rn");
}
fputs($fp,"dbname>");
fclose($fp);
}
}
?>


Usage: Insert a record

Copy code The code is as follows:


require_once('xml.class.php');
$xml = new xml("exemple .xml","item");
$newarray = array(
"title"=>"XML title",
"text"=>"PHP’s XML class test! "
);
$insert=$xml->xml_query('insert','','',$newarray);//The second and third variable positions are conditions, leaving them blank means inserting

at the end
Modify record

Copy code The code is as follows:


require_once('xml.class.php');
$xml = new xml("exemple.xml","item");
$array = array(
"title"=>"XML title",
"text"=>"PHP's XML class test!"
);
$insert=$xml->xml_query('update','title, =, What will the world be like in 20 years? ','and',$array);//Replace the title tag equal to xxx with $array (you can create a unique attribute tag, such as id, so that a certain record can be modified)


Delete record

Copy code The code is as follows:


require_once('xml.class.php');
$xml = new xml("exemple.xml","item");
$ array = array();
$insert=$xml->xml_query('update','title,=,What will the world be like in 20 years?','and',$array);//Leave the array empty


Remarks: When deleting, the value is actually made empty. We can modify xml_update() to determine the value of $array before generating the xml file. If the value is empty, it will not be written to the final array, which is the effect of deletion. . The speed of writing xml files is very fast (I have tested 30,000 records). When inserting, only one record is inserted, and the modification speed is also very fast. It is very suitable for medium-sized websites to use when generating XML, so I recommend it.

The above introduces the xinputemulator PHP class that operates XML as a database, including the content of xinputemulator. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

How to Register and Use Laravel Service Providers How to Register and Use Laravel Service Providers Mar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles