Insert data into a specific part of a file

1

I'm using the google feed database file, and I need to dynamically change the information to generate an xml file, I am using this approach, with file_puts_contents (), to put the <item> tags in the file:

file_put_contents('feed.xml', $xml, FILE_APPEND);

Only the end of the xml file has to end with this structure:

</channel>
</rss>

and FILE_APPEND is putting it down, is there any way to insert the content in a specific location or always add </channel></rss>     at the end of the loop?

EDIT: Xml standard google:

    <?xml version="1.0"?>
<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">
    <channel>
        <title>O nome do feed de dados</title>
        <link>http://www.example.com</link>
        <description>Uma descrição do conteúdo</description>

        <item>
            <title>Suéter de lã vermelho</title>
            <link> http://www.example.com/item1-info-page.html</link>
            <description>Confortável e macio, este suéter manterá você aquecido nas noites frias do inverno.</description>
            <g:image_link>http://www.example.com/image1.jpg</g:image_link>
            <g:price>25</g:price>
            <g:condition>novo</g:condition>
            <g:id>1a</g:id>
        </item>

    </channel>
</rss>
    
asked by anonymous 24.05.2017 / 23:05

1 answer

2

Considering that you want to add many <item> tags followed by </channel></rss> a possible solution is:

<?php
$xmlstr = '<?xml version="1.0"?><rss >...</description>';
// Coloca o início do xml no arquivo
file_put_contents('feed.xml', $xmlstr);

// itens recuperados do banco de dados
$items = [
            "<item><title>título 1</title><description>descrição 1</description>",
            "<item><title>título 2</title><description>descrição 2</description>",
            "<item><title>título 3</title><description>descrição 3</description>",
];

// Coloca os itens no arquivo
foreach ($items as $item) {
        file_put_contents('feed.xml', $item, FILE_APPEND);
}

// Coloca o fim do xml no arquivo
file_put_contents('feed.xml', '</channel></rss>', FILE_APPEND);

// imprime o conteúdo do arquivo na STDOUT
echo file_get_contents('feed.xml');
    
25.05.2017 / 06:30