1

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

1

2 Answers 2

1

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...

Sign up to request clarification or add additional context in comments.

10 Comments

okay after the 9 what is the 0 for. And where you have newline1 and newline2 is that where i would put information?
See the array_splice() documentation for details. 9 is the position at which to insert new elements. 0 is the number of elements after index 9 which you want to replace (none, in your case, I presume?) and those are followed by a replacement array.
okay so this looks good but it looks like you closed $fp does this still save the new text?
bad idea ... use proper xml parsing
@ajreal I know. That's why I hinted on revalidating syntax. Still there's less overhead (providede the file is relatively small) in comparison to using a XML parsing facilies, which can only parse and (if at all) reconstruct an limited way...
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.