如何使用 PHP XML reader & 更新此 xml 文件作家? [英] How to update this xml file with PHP XML reader & writer?

查看:28
本文介绍了如何使用 PHP XML reader & 更新此 xml 文件作家?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下站点地图 XML,其中包含要提交给搜索引擎的 URL 列表.我从另一个 SO 答案中获取了此示例代码.

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();

此代码使用 XML 编写器创建了一个新的站点地图.我想使用 XMLReader 将新的 url 附加到现有的 urlset

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();

我找不到有关如何使用 XMLreader 更新 xml 文件的正确示例.如何重写此代码,以便它使用 XMLreader 将新 URL 附加到 url set 标记?

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?

编辑 1:

我有这个 xml 站点地图,

I have this xml sitemap,

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

我希望程序在 urls 标签处添加一个新的 url,例如:添加网址 google.com

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>

我如何获得此功能,或者是否有其他一些帮助程序(例如 DOMDocumentsimplexml)可以在 PHP 中执行此操作?也欢迎对其他网站的任何引用.

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.

推荐答案

我正在等待一个好的回应,我有一些问题(xml 文件超过 50.000 个元素),我想添加元素而不在内存中加载完整的 xml

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

这篇关于如何使用 PHP XML reader &amp; 更新此 xml 文件作家?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆