使用php从url解析XML文件


Parse XML file from url using php

我想从另一台服务器解析xml文件。

<?php
    $xml = simplexml_load_file('http://example_page.com/api/test.xml');
?>

只有当这个文件和页面在同一个服务器上,但我在另一台服务器上有xml文件时,这些代码才能工作。

来自网页的警告:

Warning: simplexml_load_file(http://example_page.ugu.pl/api/test.xml) [function.simplexml-load-file]: failed to open stream: Connection refused in /virtual/z/y/example_page.ugu.pl/index.php on line 14
Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http://example_page.com/api/test.xml" in /virtual/z/y/example_page.ugu.ugu.pl/index.php on line 14

p.S.allow_url_fopen仍然打开。

您访问的url中似乎存在一些重定向问题,很可能simplexml_load_file()没有遵循重定向。。。

因此,解决方案是使用file_get_contents()cUrl。。。

由于file_get_contents()更容易,我展示的只是。。。

代码必须类似于:

<?php
    $xml = simplexml_load_string(file_get_contents('http://example_page.ugu.pl/api/test.xml'));
?>

更多:

<?php
    $xml = simplexml_load_string(file_get_contents('http://jakdojade.pl/pages/api/outputs/schedules.xml'));
?>

^这也完全有效!

您应该使用CURL(如果处于活动状态)。

$url = "http://www.you-web-here.com/";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$xmlString = curl_exec($curl);

PHP文档:

Note:
Libxml 2 unescapes the URI, so if you want to pass e.g. b&c as the URI parameter a, you have to call simplexml_load_file(rawurlencode('http://example.com/?a=' . urlencode('b&c'))). Since PHP 5.1.0 you don't need to do this because PHP will do it for you.

所以。你用的是哪个版本?

或者,你可以这样尝试:

$xml_content = file_get_content('http://example_page.com/api/test.xml');
xml = simplexml_load_string($xml_content);