How to update this xml file with PHP XML reader &

2019-04-16 19:16发布

I have the following sitemap XML which contains a list of URLs to be submitted for search engines. I took this example code from another SO answer.

// Init XMLWriter
$writer = new XMLWriter();
$writer->openURI(APPLICATION_PATH . '/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>some url here;  SO not allowed me</loc></url>
$writer->startElement('url');
$writer->writeElement('loc', 'some url here; SO not allowed me');
$writer->endElement();

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

This code creates a new sitemap using XML writer. I want to append new url to existing urlset using XMLReader

$reader = new XMLReader();
if (!$reader->open('sitemap.xml')){
    die("Failed to open 'sitemap.xml'");
}
while($reader->read()){
    if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'urlset') {
        $writer->startDocument('1.0', 'UTF-8');
        $writer->startElement('url');
        $writer->writeElement('loc', 'http://www.test.com');
        $writer->endElement();
        break;
    }
}
$reader->close();

I could not find proper samples on how to update xml file with XMLreader. How can I rewrite this code so that it appends new URLs to url set tag using XMLreader?

Edit 1:

I have this xml sitemap,

<?xml version="1.0" encoding="UTF-8"?>
<urls>
    <url>
     <loc>http://www.bbc.com</loc>
    </url>
</urls>

I want the program to add one new url at the urls tag like this eg. adding URL google.com,

<?xml version="1.0" encoding="UTF-8"?>
<urls>
    <url>
     <loc>http://www.bbc.com</loc>
    </url>
    <url>
     <loc>http://www.google.com</loc>
    </url>
</urls>

How could I get this functionality or is there some other helpers like DOMDocument or simplexml to do that in PHP? Any references to others sites is also welcome.

2条回答
放我归山
2楼-- · 2019-04-16 19:41

XMLWriter is not good for this methodology. You should use a different library, like simplexml for instance.

With that, it's very simple. Although I don't know what your doc structure looks like, let's take a stab at it:

//load the file for our manipulating
$xml = simplexml_load_file($file);

//grab the parent element that we want to append to
$urls = $xml->urls;

//add a new child called Url
$newUrl = $urls->addChild('url');

//add a new child called loc to the new child Url we just created, add a link to yahoo
$newUrl->addChild('loc', 'http://www.yahoo.com');

//write the output
$xml->asXML($xml);

Here's an eval.in example

查看更多
神经病院院长
3楼-- · 2019-04-16 20:01

I waiting for a good response, I have the some problem (xml file with over 50.000 elements) and I would like to add element without load full xml in memory

查看更多
登录 后发表回答