[thelist] PHP - insert text at specific place in file?

Mark Groen evolt at markgroen.com
Tue Feb 20 12:42:46 CST 2007


On Tuesday 20 February 2007 10:15, Brent Eades wrote:
> OK, here's what I'm aiming for. I have an input form which is meant to
> simultaneously write both an HTML 'news' file and an equivalent RSS
> file, using variables passed from the form.
>
> I have the HTML part mostly figured out -- I can append new news items
> at the top of the file, where I want them.
>
> But for the RSS file, new items would of course have to be inserted at a
> particular point in the file, specifically, immediately after the
> closing </channel> element. Here's a snippet showing what I mean:
>
> print "<channel>";
>    [snip]
> print "</channel>";
>    [want to insert new item here, e.g.:]
> $item .= "<item rdf:about=\"http://foo/" . $newURL . "\">";
> $item .= "<title>" . $newtitle . "</title>";
>    [snip]
> $item .= "</item>\n";
>    [snip]
> $fh = fopen('file.xml'...);
>
> So what I need to do is open 'file.xml', find the </channel> element,
> and then insert a new <item> above any pre-existing <items>. Is there a
> way of doing something like this in PHP, perhaps using preg_match or
> something along those lines?

There may be an easier way, just have your feed page use an include for the 
top and bottom elements of the rss/xml file:

1st include file contents:
echo '<rss version="0.92"><channel><title>In the News</title>
<description>People and Places in the Media</description>';

then modify (if needed) kzevian's snippet:

http://ca3.php.net/fwrite

another include for the bottom:

echo '</channel></rss>';

Something like that should work, there should be other ways too - there always 
is with php and the above isn't very elegant with those includes but...

HTH!
-- 
cheers,

        mark



More information about the thelist mailing list