我在 HTTP POST from PHP, without cURL
找到了这个示例PHP源代码我需要一些帮助来修改示例PHP源代码,以支持 XML DOM 来操作REST API。
我想如果我从
更新下面的 CASE语句部分$r = simplexml_load_string($res);
到
$r = new DOMDocument();
$r->load($res);
它会起作用,但事实并非如此。 :(
任何帮助将不胜感激。
function rest_helper($url, $params = null, $verb = 'GET', $format = 'xml')
{
$cparams = array(
'http' => array(
'method' => $verb,
'ignore_errors' => true
)
);
if ($params !== null) {
$params = http_build_query($params);
if ($verb == 'POST') {
$cparams['http']['content'] = $params;
} else {
$url .= '?' . $params;
}
}
$context = stream_context_create($cparams);
$fp = fopen($url, 'rb', false, $context);
if (!$fp) {
$res = false;
} else {
// If you're trying to troubleshoot problems, try uncommenting the
// next two lines; it will show you the HTTP response headers across
// all the redirects:
// $meta = stream_get_meta_data($fp);
// var_dump($meta['wrapper_data']);
$res = stream_get_contents($fp);
}
if ($res === false) {
throw new Exception("$verb $url failed: $php_errormsg");
}
switch ($format) {
case 'json':
$r = json_decode($res);
if ($r === null) {
throw new Exception("failed to decode $res as json");
}
return $r;
case 'xml':
$r = simplexml_load_string($res);
if ($r === null) {
throw new Exception("failed to decode $res as xml");
}
return $r;
}
return $res;
}
答案 0 :(得分:0)
正确的形式是:
$r = new DOMDocument();
$r->loadXML($res);
请参阅DOMDocument::loadXML的文档从文件中加载DOMDocument::load()
方法。