使用 PHP 写入文件

发布于 2024-10-08 07:53:05 字数 148 浏览 0 评论 0原文

基本上我想做的是使用 PHP 打开一个 xml 文件并使用 php 编辑它,现在我可以使用 fopen() 函数来做到这一点。 但我的问题是我想将文本附加到文档的中间。假设 xml 文件有 10 行,我想在最后一行 (10) 之前附加一些内容,所以现在将是 11 行。这可能吗?谢谢

Bassicly what I want to do is using PHP open a xml file and edit it using php now this I can do using fopen() function.
Yet my issue it that i want to append text to the middle of the document. So lets say the xml file has 10 lines and I want to append something before the last line (10) so now it will be 11 lines. Is this possible. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜`诱少女 2024-10-15 07:53:05

根据该文件的大小,您可能会这样做:

$lines = array();
$fp = fopen('file.xml','r');
while (!feof($fp))
   $lines[] = trim(fgets($fp));
fclose($fp);

array_splice($lines, 9, 0, array('newline1','newline2',...));

$new_content = implode("\n", $lines);

不过,您之后仍需要重新验证 XML 语法...

Depending on how large that file is, you might do:

$lines = array();
$fp = fopen('file.xml','r');
while (!feof($fp))
   $lines[] = trim(fgets($fp));
fclose($fp);

array_splice($lines, 9, 0, array('newline1','newline2',...));

$new_content = implode("\n", $lines);

Still, you'll need to revalidate XML-syntax afterwards...

梦魇绽荼蘼 2024-10-15 07:53:05

如果您希望能够从中间修改文件,请使用c+打开模式:

$fp = fopen('test.txt', 'c+');

for ($i=0;$i<5;$i++) {
   fgets($fp);
}

fwrite($fp, "foo\n");
fclose($fp);

上面将在第五行写入“foo”,而不必完全读取文件。

但是,如果您要修改 XML 文档,那么使用 DOM 解析器可能会更好:

$dom = new DOMDocument;
$dom->load('myfile.xml');

$linenum = 5;
$newNode = $dom->createElement('hello', 'world');

$element = $dom->firstChild->firstChild; // skips the root node
while ($element) {
    if ($element->getLineNo() == $linenum) {
        $element->parentNode->insertBefore($newNode, $element);
        break;
    }
    $element = $element->nextSibling;
}

echo $dom->saveXML();

当然,上面的代码取决于实际的 XML 文档结构。但是,$element->getLineNo() 是这里的关键。

If you want to be able to modify a file from the middle, use the c+ open mode:

$fp = fopen('test.txt', 'c+');

for ($i=0;$i<5;$i++) {
   fgets($fp);
}

fwrite($fp, "foo\n");
fclose($fp);

The above will write "foo" on the fifth line, without having to read the file entirely.

However, if you are modifying a XML document, it's probably better to use a DOM parser:

$dom = new DOMDocument;
$dom->load('myfile.xml');

$linenum = 5;
$newNode = $dom->createElement('hello', 'world');

$element = $dom->firstChild->firstChild; // skips the root node
while ($element) {
    if ($element->getLineNo() == $linenum) {
        $element->parentNode->insertBefore($newNode, $element);
        break;
    }
    $element = $element->nextSibling;
}

echo $dom->saveXML();

Of course, the above code depends on the actual XML document structure. But, the $element->getLineNo() is the key here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文