php 如何在php中回显xml文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1199595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:29:44  来源:igfitidea点击:

How to echo xml file in php

phpxml

提问by chris

How to print an xml file to the screen in php?

如何在php中将xml文件打印到屏幕上?

This is not working:

这不起作用:

$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;

Is there a simple solution? Maybe without SimpleXML?

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

回答by Josh Davis

You can use HTTP URLs as if they were local files, thanks to PHP's wrappers

由于PHP 的包装器,您可以像使用本地文件一样使用 HTTP URL

You can get the contents from an URL via file_get_contents() and then echo it, or even read it directly using readfile()

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

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

or

或者

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

Don't forget to set the correct MIME type before outputing anything, though.

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

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

回答by GabLeRoux

Here's what worked for me:

以下是对我有用的内容:

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

Using htmlspecialcharswill prevent tags from being displayed as html and won't break anything. Note that I'm using Prettyprintto highlight the code ;)

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

回答by Cristian Toma

You can use the asXMLmethod

您可以使用asXML方法

echo $xml->asXML();

You can also give it a filename

你也可以给它一个文件名

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

回答by Tom Haigh

If you just want to print the raw XML you don't need Simple XML. I added some error handling and a simple example of how you might want to use SimpleXML.

如果您只想打印原始 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;   
}

回答by Sampson

Am I oversimplifying this?

我是否过于简单化了?

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

Some places (like digg.com) won't allow you to access their site without having a user-agent, in which case you would need to set that with ini_set() prior to running the file_get_contents().

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

回答by mikl

To display the html/xml "as is" (i.e. all entities and elements), simply escape the characters <, &, and enclose the result with <pre>:

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

$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>';

Prints:

印刷:

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

Tested on Chrome 45

在 Chrome 45 上测试

回答by jim

This worked for me:

这对我有用:

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

回答by ShapCyber

If anyone is targeting yahoo rss feed may benefit from this snippet

如果有人针对雅虎 rss 提要可能会从这个片段中受益

<?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);
?>

You may want to run it in your browser first to see what is there and before looping and style it up pretty simple

您可能希望首先在浏览器中运行它以查看那里有什么,然后再循环并设置非常简单的样式

To grab the first item description

抓取第一个项目描述

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

You can see a demo here

你可以在这里看到一个演示

回答by Null

This works:

这有效:

<?php
$XML = "<?xml version='1.0' encoding='UTF-8'?>
<!-- Your XML -->
";

header('Content-Type: application/xml; charset=utf-8');
echo ($XML);
?>

回答by Kevin Pareek

The best solution is to add to your apache .htaccessfile the following line after RewriteEngine On

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

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

and then simply having a file sitemap.phpin your root folder that would be normally accessible via http://www.yoursite.com/sitemap.xml, the default URL where all search engines will firstly search.

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

The file sitemap.phpshall start with

该文件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>

it works :)

有用 :)