你必须分两步进行:
- Get the XML string from the remote server
- with curl http://www.php.net/curl, 例如
- or with 文件获取内容 http://www.php.net/file_get_contents
- and, then, parse that XML to extract the data
- with simplexml_load_string http://www.php.net/manual/en/function.simplexml-load-string.php例如
请注意,这两个步骤可以合并为一个,使用simplexml_load_file http://www.php.net/simplexml_load_file,如果您的服务器配置允许您这样做。
一旦您将 XML 放入 PHP 变量中,使用 SimpleXML 就可以很容易地获得您想要的值。例如 :
$string = '<?xml version="1.0" ?><Tracker>12345</Tracker>';
$xml = simplexml_load_string($string);
echo (string)$xml;
会得到你
12345
从远程 URL 获取 XML 的内容非常简单:
$string = file_get_contents('http://your-remote-url');
如果您能做到这一点,您还可以直接通过 SimpleXML 使用该远程 URL:
$xml = simplexml_load_file('http://your-remote-url');
echo (string)$xml;
但这只有在以下情况下才有效allow_url_fopen http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen在您的服务器配置中启用。
If allow_url_fopen
在您的服务器上禁用,您可以使用curl从远程服务器获取XML;像这样的事情应该可以解决问题,例如:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://your-remote-url");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$string = curl_exec($ch);
curl_close($ch);
然后,您仍然可以使用simplexml_load_string
,正如我在第一个示例中所做的那样。
(如果使用curl,请查看文档curl_setopt http://www.php.net/manual/en/function.curl-setopt.php:有几个选项可能会让您感兴趣——例如,指定超时)