解析位于互联网上的xml文档并转换为json

时间:2009-04-15 18:50:06

标签: php xml json

我找到http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/,但我不知道如何使用此代码从我的网络服务器获取xml。任何想法?

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用file_get_contents()

$xmlString = file_get_contents('http://www...../file.xml');

如果您需要SimpleXML对象,可以使用simplexml_load_file()

$xml = simplexml_load_file('http://www...../file.xml');

这两种方法都需要启用allow_url_fopen。如果不是,您可以使用curl - 这更复杂,但也为您提供更大的灵活性。

$c = curl_init('http://www...../file.xml');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);

$xmlString = curl_exec($c);
$error = curl_error($c);
curl_close($c);

if ($error)
    die('Error: ' . $error);