Hướng dẫn how to store data in xml file using php - cách lưu trữ dữ liệu trong tệp xml bằng php

Giao diện

        interface OutputType
        {
            public function generate[];
        }

Lớp XMLFILE

            //import the interface above

        class XMLType implements OutputType
        {
            protected $xml;

            protected $parentElement;
            protected $elementGroup;


            protected $parentList = [];
            protected $elementList = [];

            public function __construct[]
            {
                $this->xml= new \DOMDocument['1.0', 'ISO-8859-15'];
            }

            public function createParent[$type, $attributes = []]
            {
                $this->parentElement = $this->xml->createElement[$type];
                $this->addAttributes[$this->parentElement, $attributes];

                return $this;
            }

            private function addAttributes[&$element, $attributes]
            {
                if [sizeof[$attributes] > 0] {
                    foreach[$attributes as $type => $value] {
                        $element->setAttribute[$type, $value];
                    }
                }
            }

            public function addElement[$type, $element, $attributes = []]
            {
                 $this->elementGroup  = $this->xml->createElement[$type, $element];
                 $this->addAttributes[$this->elementGroup, $attributes];
                 $this->elementList[] = $this->elementGroup;
                 return $this;
            }

            /**
             *  We wish to trigger this every time you want to ad d a new parent to
             *  hold new elements! So the program knows to close
             *  the previous one before starting a new and mesh all into one single
             *  element, which we do not want to!
            **/
            public function groupParentAndElements[]
            {
                foreach[$this->elementList as $prevElements] {
                    $this->parentElement->appendChild[$prevElements];
                }

                $this->parentList[] = $this->parentElement;
                $this->elementList = [];

                return $this;
            }

            public function generate[]
            {
                //Uses filled parentList where each parent contains its child elements to generate the XML
                foreach [$this->parentList as $prevParent] {
                    $this->xml->appendChild[$prevParent];    
                }

                //here I am saving and printing but you can change to suit your needs.
                //It is at this point it is ready to generate the XML
                print $this->xml->saveXML[]; 
            } 

        }

Nơi bạn muốn sử dụng lớp XML

            if [isset[$_POST['submit']]] {
                $xmlType = new XMLType[];
                $xmlType->createParent['programme', ['id' => 1]]
                        ->addElement['name', $_POST['name'], ['type' => 'string']]
                        ->addElement['description', $_POST['description']]
                        ->addElement['mood', $_POST['mood']]
                        ->groupParentAndElements[]
                        ->createParent['others', ['id' => 2, 'attr' => 'ex']]
                        ->addElement['example', 'A value here']
                        ->groupParentAndElements[];

                //whenever you wish to output
                $xmlType->generate[];
            }

Đầu ra

            
                
                    //your post name
                
                
                    //your post description
                
                
                    //your post mood
                
            
            
               
                   A value here
               
            

Đối với lớp, bạn luôn có thể thêm các yếu tố bổ sung như ghi chú, loại, v.v., nó sẽ tùy thuộc vào nhu cầu XML của bạn. Chỉ cần theo cấu trúc hoặc thậm chí đi xa hơn :]

ví dụ mã làm việc

Lưu trữ nội dung XML vào một tệp

interface FileCreationContract
{
    public function create[$content];
}


class XMLFile implements FileCreationContract
{

    const REGEX_EXTENTION_LOOKOUT = '/\.[^.]+$/';
    const EXTENTION = '.xml';

    protected $path;
    protected $filename;

    public function __construct [$filename, $path = '']
    {
        $this->filename = $filename;
        $this->parseFilename[];

        if [empty[$this->path]] {
            $this->path = realpath[__DIR__];
        }
    }

    /**
     * If programmer mistakes and adds extention, removes it to make sure the wrong extention was not added;
     */
    private function parseFilename[]
    {
        if [ strpos[$this->filename, self::EXTENTION] === FALSE ] {
            $this->filename = preg_replace[self::REGEX_EXTENTION_LOOKOUT, '', $this->filename] . self::EXTENTION;
        }

        if [empty[$this->filename]] {
            $this->filename = 'default-name'.self::EXTENTION;
        }
    }

    /**
     * @return mixed
     */
    public function getPath []
    {
        return $this->path;
    }

    /**
     * @param mixed $path
     *
     * @return XMLFile
     */
    public function setPath [$path]
    {
        $this->path = $path;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getFilename []
    {
        return $this->filename;
    }

    /**
     * @param mixed $filename
     *
     * @return XMLFile
     */
    public function setFilename [$filename]
    {
        $this->filename = $filename;
        $this->parseFilename[];
        return $this;
    }

    public function create [$content]
    {
        $file = fopen[$this->path.$this->filename, 'w'] or die["Unable too open file!"]; //I recommend throwing an exception here!
        fwrite[$file, $content];
        fclose[$file];
    }

}    

Tại bộ điều khiển của bạn, sau khi xây dựng nội dung XML

...
$xmlFile = new XMLFile['database.php', 'path/to/your/public/folder/'];
$xmlFile->create[$xmlType->generate[]];
...

Lưu ý: Thay thế print thành return trên phương thức generate[] của bạn từ lớp XMLType Replace print to return on your generate[] method from XMLType class

Lớp học mới này sẽ đảm bảo tên tệp của bạn theo định dạng ____1010 dự kiến ​​để lưu. Bạn luôn có thể ghi đè đường dẫn để lưu tệp ở cấp độ xây dựng hoặc gọi

            //import the interface above

        class XMLType implements OutputType
        {
            protected $xml;

            protected $parentElement;
            protected $elementGroup;


            protected $parentList = [];
            protected $elementList = [];

            public function __construct[]
            {
                $this->xml= new \DOMDocument['1.0', 'ISO-8859-15'];
            }

            public function createParent[$type, $attributes = []]
            {
                $this->parentElement = $this->xml->createElement[$type];
                $this->addAttributes[$this->parentElement, $attributes];

                return $this;
            }

            private function addAttributes[&$element, $attributes]
            {
                if [sizeof[$attributes] > 0] {
                    foreach[$attributes as $type => $value] {
                        $element->setAttribute[$type, $value];
                    }
                }
            }

            public function addElement[$type, $element, $attributes = []]
            {
                 $this->elementGroup  = $this->xml->createElement[$type, $element];
                 $this->addAttributes[$this->elementGroup, $attributes];
                 $this->elementList[] = $this->elementGroup;
                 return $this;
            }

            /**
             *  We wish to trigger this every time you want to ad d a new parent to
             *  hold new elements! So the program knows to close
             *  the previous one before starting a new and mesh all into one single
             *  element, which we do not want to!
            **/
            public function groupParentAndElements[]
            {
                foreach[$this->elementList as $prevElements] {
                    $this->parentElement->appendChild[$prevElements];
                }

                $this->parentList[] = $this->parentElement;
                $this->elementList = [];

                return $this;
            }

            public function generate[]
            {
                //Uses filled parentList where each parent contains its child elements to generate the XML
                foreach [$this->parentList as $prevParent] {
                    $this->xml->appendChild[$prevParent];    
                }

                //here I am saving and printing but you can change to suit your needs.
                //It is at this point it is ready to generate the XML
                print $this->xml->saveXML[]; 
            } 

        }
1 để thay thế nó, trước khi bạn gọi
            //import the interface above

        class XMLType implements OutputType
        {
            protected $xml;

            protected $parentElement;
            protected $elementGroup;


            protected $parentList = [];
            protected $elementList = [];

            public function __construct[]
            {
                $this->xml= new \DOMDocument['1.0', 'ISO-8859-15'];
            }

            public function createParent[$type, $attributes = []]
            {
                $this->parentElement = $this->xml->createElement[$type];
                $this->addAttributes[$this->parentElement, $attributes];

                return $this;
            }

            private function addAttributes[&$element, $attributes]
            {
                if [sizeof[$attributes] > 0] {
                    foreach[$attributes as $type => $value] {
                        $element->setAttribute[$type, $value];
                    }
                }
            }

            public function addElement[$type, $element, $attributes = []]
            {
                 $this->elementGroup  = $this->xml->createElement[$type, $element];
                 $this->addAttributes[$this->elementGroup, $attributes];
                 $this->elementList[] = $this->elementGroup;
                 return $this;
            }

            /**
             *  We wish to trigger this every time you want to ad d a new parent to
             *  hold new elements! So the program knows to close
             *  the previous one before starting a new and mesh all into one single
             *  element, which we do not want to!
            **/
            public function groupParentAndElements[]
            {
                foreach[$this->elementList as $prevElements] {
                    $this->parentElement->appendChild[$prevElements];
                }

                $this->parentList[] = $this->parentElement;
                $this->elementList = [];

                return $this;
            }

            public function generate[]
            {
                //Uses filled parentList where each parent contains its child elements to generate the XML
                foreach [$this->parentList as $prevParent] {
                    $this->xml->appendChild[$prevParent];    
                }

                //here I am saving and printing but you can change to suit your needs.
                //It is at this point it is ready to generate the XML
                print $this->xml->saveXML[]; 
            } 

        }
2;

Chúng ta có thể lưu trữ dữ liệu trong XML không?

Các tài liệu XML bạn chèn vào các cột của loại XML có thể nằm trong đối tượng lưu trữ mặc định hoặc trực tiếp trong hàng bảng cơ sở. Lưu trữ hàng bảng cơ sở nằm dưới sự kiểm soát của bạn và chỉ có sẵn cho các tài liệu nhỏ; Các tài liệu lớn hơn luôn được lưu trữ trong đối tượng lưu trữ mặc định.. Base table row storage is under your control and is available only for small documents; larger documents are always stored in the default storage object.

Làm thế nào chúng ta tạo tệp XML thông qua mã PHP?

Cách tạo tài liệu XML bằng PHP..
Tiết $ dom = new domdocument [];Tạo một thể hiện của lớp DomDocument ..
Tiết $ Dom-> mã hóa = 'UTF-8';Đặt mã hóa tài liệu thành UTF-8 ..
Tiết $ Dom-> xmlversion = '1.0';Chỉ định phiên bản số 1.0 ..
Tiết $ DOM-> định dạngtOutput = true;đảm bảo rằng đầu ra được định dạng tốt ..

Làm cách nào để lưu tệp XML?

Lưu dữ liệu XML trong các ô được ánh xạ vào tệp dữ liệu XML..
Nhấn Ctrl+s để lưu tệp của bạn.....
Nhấp vào Tệp> Lưu dưới dạng và chọn vị trí mà bạn muốn lưu tệp.....
Trong hộp tên tệp, nhập tên cho tệp dữ liệu XML ..
Trong danh sách lưu dưới dạng loại, nhấp vào dữ liệu XML và nhấp vào Lưu ..

Làm thế nào nhận được dữ liệu từ URL XML trong PHP?

$ url = '//www.example.com';$ xml = simplexml_load_file [$ url, "simplexmlelement", libxml_nocdata];$ url có thể là tệp PHP, miễn là tệp tạo dữ liệu định dạng XML làm đầu ra.Lưu câu trả lời này. $url can be php file, as long as the file generate xml format data as output. Save this answer.

Bài Viết Liên Quan

Chủ Đề