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.
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:
Here's an eval.in example
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