dongwen2896 2014-08-28 10:30
浏览 98
已采纳

如何从php中的文本文件中的文本中输出xml

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

  • 写回答

2条回答 默认 最新

  • drrhr20884 2014-08-28 11:17
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存