pmesco
pmesco

Reputation: 29

How to make xml out from text inside a text file in php

How to make xml out from text inside a text file in php?
I have a code but it brings me error "Extra content at the end of the document".

Below is my code:

<?php
header('Content-Type: application/xml');
$lines = file('file.txt');
echo '<?xml version="1.0" encoding="UTF-8"?>';
foreach($lines as $line){
   $output = '<url><loc>http://example.com/'.$line.'.html</loc></url>';
   echo $output;
}

here is example text file:

page1
page2
page3
page4

sample output:

<url>
   <loc>http://example.com/page1.html</loc>
</url>
<url>
   <loc>http://example.com/page2.html</loc>
</url>
<url>
   <loc>http://example.com/page3.html</loc>
</url>
<url>
   <loc>http://example.com/page4.html</loc>
</url>

I will need to use these for sitemap.xml

Upvotes: 0

Views: 100

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76415

The XML error "Extra content at the end of the document" is quite simple. By definition, a valid XML DOM must have one, and only one, single root note, which contains the entire dataset. You don't have this. Your output is:

<?xml version="1.0"?>
<url>
   <loc>http://example.com/page1.html</loc>
</url>
<url>
   <loc>http://example.com/page2.html</loc>
</url>
<url>
   <loc>http://example.com/page3.html</loc>
</url>
<url>
   <loc>http://example.com/page4.html</loc>
</url>

Whereas valid XML would be:

<?xml version="1.0" encoding="UTF-8"?>
    <sitemap>
        <url>
            <loc>http://example.com/page1.html</loc>
        </url>
        <url>
           <loc>http://example.com/page2.html</loc>
        </url>
        <url>
           <loc>http://example.com/page3.html</loc>
        </url>
        <url>
           <loc>http://example.com/page4.html</loc>
        </url>
    </sitemap>

So the simple fix in your case would be:

header('Content-type: application/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>
<sitemap>';
$lines = file(
    'file.txt',
    //do not line-breaks to XML values, and skip empty values, to avoid empty tags
    FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES
);
foreach ($lines as $line)
{
    echo '<url><loc>http://example.com/', $line, '.html'</loc></url>';
}
echo '</sitemap';

But really, I'd recommend you think about how to best structure your DOM, and how you can use DOM parsers to reliably construct the markup. And after that, I'd strongly recommend you write the file to disk, instead of generating it every single time you need it.

Upvotes: 1

You can use file_put_contents in php to write into file

Upvotes: 1

Related Questions