【问题标题】:How to echo XML file in PHP如何在 PHP 中回显 XML 文件
【发布时间】:2010-11-15 00:52:22
【问题描述】:

如何在 PHP 中将 XML 文件打印到屏幕上?

这不起作用:

$curl = curl_init();        
curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');   
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);   
$result = curl_exec ($curl);   
curl_close ($curl);    
$xml = simplexml_load_string($result);
echo $xml;

有简单的解决方案吗?也许没有 SimpleXML?

【问题讨论】:

  • XML 是一种基于字符串的格式。 SimpleXML 将 XML 转换为 PHP 对象,以便在 PHP 中进行操作。如果您想显示 XML,只需回显 XML 字符串,并且如上所述,不要忘记添加正确的 HTTP 响应标头。这就是指示 HTTP 客户端将文件视为 XML 文件的原因。

标签: php xml


【解决方案1】:

感谢PHP's wrappers,您可以像使用本地文件一样使用 HTTP URL

您可以通过 file_get_contents() 从 URL 中获取内容,然后回显它,甚至可以使用 readfile() 直接读取它

$file = file_get_contents('http://example.com/rss');
echo $file;

readfile('http://example.com/rss');

不过,不要忘记在输出任何内容之前设置正确的 MIME 类型。

header('Content-type: text/xml');

【讨论】:

  • 要在 HTML 文件中回显 XML 内容,我必须使用 echo htmlentities($file) 来显示原始 XML(标签和内容)。有没有更好的办法?
【解决方案2】:

这对我有用:

<pre class="prettyprint linenums">
    <code class="language-xml"><?php echo htmlspecialchars(file_get_contents("example.xml"), ENT_QUOTES); ?></code>
</pre>

使用htmlspecialchars 将阻止标签显示为html,并且不会破坏任何内容。请注意,我使用Prettyprint 突出显示代码;)

【讨论】:

    【解决方案3】:

    你可以使用asXML方法

    echo $xml->asXML();
    

    你也可以给它一个文件名

    $xml->asXML('filename.xml');
    

    【讨论】:

    • 这会添加标题吗? header('Content-type: text/xml');
    【解决方案4】:

    这对我有用:

    echo(header('content-type: text/xml'));
    

    【讨论】:

    • 确认这适用于一个非常大的 xml 文档。
    【解决方案5】:

    如果您只想打印原始 XML,则不需要 Simple XML。我添加了一些错误处理和一个简单示例,说明您可能希望如何使用 SimpleXML。

    <?php 
    $curl = curl_init();        
    curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');   
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);   
    $result = curl_exec ($curl);   
    
    if ($result === false) {
        die('Error fetching data: ' . curl_error($curl));   
    }
    curl_close ($curl);    
    
    //we can at this point echo the XML if you want
    //echo $result;
    
    //parse xml string into SimpleXML objects
    $xml = simplexml_load_string($result);
    
    if ($xml === false) {
        die('Error parsing XML');   
    }
    
    //now we can loop through the xml structure
    foreach ($xml->channel->item as $item) {
        print $item->title;   
    }
    

    【讨论】:

      【解决方案6】:

      我是否过于简单化了?

      $location = "http://rss.news.yahoo.com/rss/topstories";
      print file_get_contents($location);
      

      有些地方(例如 digg.com)不允许您在没有用户代理的情况下访问他们的网站,在这种情况下,您需要在运行 file_get_contents() 之前使用 ini_set() 进行设置。

      【讨论】:

        【解决方案7】:

        要“按原样”显示 html/xml(即所有实体和元素),只需将字符 & 转义,并将结果用 括起来>

        $XML = '<?xml version="1.0" encoding="UTF-8"?>
        <root>
            <foo>ó</foo>
            <bar>&#xF3;</bar>
        </root>';
        
        $XML = str_replace('&', '&amp;', $XML);
        $XML = str_replace('<', '&lt;', $XML);
        echo '<pre>' . $XML . '</pre>';
        

        打印:

        <?xml version="1.0" encoding="UTF-8"?>
        <root>
            <foo>ó</foo>
            <bar>&#xF3;</bar>
        </root>
        

        在 Chrome 45 上测试

        【讨论】:

        • $XML = str_replace('>', '>', $XML);
        【解决方案8】:

        如果有人以 yahoo RSS 提要为目标,可能会从这个 sn-p 中受益

        <?php
            $rssUrl="http://news.yahoo.com/rss/topstories";
            //====================================================
            $xml=simplexml_load_file($rssUrl) or die("Error: Cannot create object");
            //====================================================
            $featureRss =  array_slice(json_decode(json_encode((array) $xml ),  true ), 0 );
         /*Just to see what is in it 
        use this function PrettyPrintArray() 
        instead of var_dump($featureRss);*/
        
            function PrettyPrintArray($rssData, $level) {
            foreach($rssData as $key => $Items) {
            for($i = 0; $i < $level; $i++)
            echo("&nbsp;");
            /*if content more than one*/
            if(!is_array($Items)){
            //$Items=htmlentities($Items); 
            $Items=htmlspecialchars($Items);
            echo("Item " .$key . " => " . $Items . "<br/><br/>");
            }
            else 
            {
            echo($key . " => <br/><br/>");
            PrettyPrintArray($Items, $level+1);
            }
            }
            }
            PrettyPrintArray($featureRss, 0);
        ?>
        

        你可能想先在浏览器中运行它,看看里面有什么,然后再循环和设计它的样式很简单

        获取第一个项目描述

        <?php
            echo($featureRss['channel']['item'][0]['description']);
        ?>
        

        You can see a demo here

        【讨论】:

          【解决方案9】:

          这行得通:

          <?php
          $XML = "<?xml version='1.0' encoding='UTF-8'?>
          <!-- Your XML -->
          ";
          
          header('Content-Type: application/xml; charset=utf-8');
          echo ($XML);
          ?>
          

          【讨论】:

            【解决方案10】:

            最好的解决方案是在您的 apache .htaccess 文件中添加 RewriteEngine On 之后的以下行

            RewriteRule ^sitemap\.xml$ sitemap.php [L]
            

            然后只需在您的根文件夹中添加一个文件 sitemap.php,该文件通常可以通过 http://www.yoursite.com/sitemap.xml(所有搜索引擎首先搜索的默认 URL)访问。

            文件sitemap.php应以

            开头
            <?php
            //Saturday, 11 January 2020 @kevin
            
            header('Content-type: text/xml');
            echo '<?xml version="1.0" encoding="UTF-8"?>';
            ?>
            <urlset
                  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
                        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
            
            <url>
              <loc>https://www.yoursite.com/</loc>
              <lastmod>2020-01-08T13:06:14+00:00</lastmod>
              <priority>1.00</priority>
            </url>
            
            
            </urlset>
            

            它有效:)

            【讨论】:

              猜你喜欢
              • 2014-03-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-04-01
              • 1970-01-01
              • 2021-09-25
              • 2011-10-17
              相关资源
              最近更新 更多