如何在php中回显xml文件

chr*_*ris 32 php xml

如何在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;
Run Code Online (Sandbox Code Playgroud)

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

Jos*_*vis 60

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

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

$file = file_get_contents('http://example.com/rss');
echo $file;
Run Code Online (Sandbox Code Playgroud)

要么

readfile('http://example.com/rss');
Run Code Online (Sandbox Code Playgroud)

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

header('Content-type: text/xml');
Run Code Online (Sandbox Code Playgroud)


Gab*_*oux 15

这对我有用:

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

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


Cri*_*oma 7

您可以使用asXML方法

echo $xml->asXML();
Run Code Online (Sandbox Code Playgroud)

你也可以给它一个文件名

$xml->asXML('filename.xml');
Run Code Online (Sandbox Code Playgroud)


Tom*_*igh 5

如果只想打印原始XML,则不需要简单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;   
}
Run Code Online (Sandbox Code Playgroud)


jim*_*jim 5

这对我有用:

echo(header('content-type: text/xml'));
Run Code Online (Sandbox Code Playgroud)