简体   繁体   中英

Write data to xml using XML Parser in PHP

this is my question in XML and new to this. i was struggle with creating a xml file using xml parser in php. my requirement is read array which contains data to write in xml. how to process the array for writing data into xml file. i tried to write a single data in xml but i didn't create a xml file otherwise it just display the data in browser.

[1]: http://www.phpbuilder.com/board/showthread.php?t=10356853 i used the code in the link but i didn't create a xml file. how to create.xml file using xml parser in php.

I post here a sample code I use to generate a sitemap.xml file on a website. You may find it useful.

    // Init XMLWriter
    $writer = new XMLWriter();
    $writer->openURI(APPLICATION_PATH . '/public/sitemap.xml');

    // document head
    $writer->startDocument('1.0', 'UTF-8');
    $writer->setIndent(4);
    $writer->startElement('urlset');
    $writer->writeAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

    // Write something
    // this will write: <url><loc>http://www.mysite.com</loc></url>
    $writer->startElement('url');
    $writer->writeElement('loc', 'http://www.mysite.com');
    $writer->endElement();

    // end urlset
    $writer->endElement();
    // end document
    $writer->endDocument();

This will create a sitemap.xml file in the public directory. Make sure PHP has writing rights on the target directory. Usually, on Linux+Apache, giving writing rights to the www-data user on this directory does the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM