当前位置: 动力学知识库 > 问答 > 编程问答 >

php - file_get_contents() removes XML tags

问题描述:

In the browser the following url http://kulturarvsdata.se/raa/fmi/xml/10028201230001 shows up as a regular XML file. but when I'm using

file_get_contents('http://kulturarvsdata.se/raa/fmi/xml/10028201230001');

it removes all XML tags and just returns the containing text. Why is this happening and how do I avoid it?

Some response headers:

array(5) {

[0]=> string(15) "HTTP/1.1 200 OK"

[1]=> string(35) "Date: Thu, 01 Jan 2015 20:07:04 GMT"

[2]=> string(25) "Server: Apache-Coyote/1.1"

[3]=> string(43) "Content-Type: application/xml;charset=UTF-8"

[4]=> string(17) "Connection: close"

}

网友答案:

Unable to reproduce:

<?php
/**
 * http://stackoverflow.com/questions/27733997/file-get-contents-removes-xml-tags
 */

header('Content-Type: text/plain; charset=utf-8');
echo substr(file_get_contents('http://kulturarvsdata.se/raa/fmi/xml/10028201230001'), 0, 256);

<?xml version="1.0" encoding="UTF-8"?><pres:item xmlns:pres="http://kulturarvsdata.se/presentation#"><pres:id>10028201230001</pres:id><pres:entityUri>http://kulturarvsdata.se/raa/fmi/10028201230001</pres:entityUri><pres:type>Kulturlämning</pres:type><pres

So answer is: Works fine.

You perhaps look at the response in the browser which removes the tags? This at least would be a common mistake some users on Stackoverflow ask about.

网友答案:

Please try this

simplexml_load_file — Interprets an XML file into an object

<?php
// The file test.xml contains an XML document with a root element
// and at least an element /[root]/title.

if (file_exists('test.xml')) {
    $xml = simplexml_load_file('test.xml');

    print_r($xml);
} else {
    exit('Failed to open test.xml.');
}
?>
网友答案:

Had the same problem and I solved it changing the way of fetching the information, so instead of using file_get_contents, I used curl:

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_REFERER, 'http://www.google.com/');
curl_setopt ($ch, CURLOPT_TIMEOUT, 10);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec ($ch);
curl_close ($ch);
分享给朋友:
您可能感兴趣的文章:
随机阅读: