0

我在 PHP 的HTTP POST 中找到了这个示例 PHP 源代码,没有 cURL

我需要一些帮助来修改示例 PHP 源代码以支持XML DOM来操作 REST API。

我想如果我从下面的 XML 部分更新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;
}
4

1 回答 1

0

正确的形式是:

$r = new DOMDocument();
$r->loadXML($res);

请参阅DOMDocument::loadXML的文档该DOMDocument::load()方法从文件加载。

于 2010-06-01T20:44:04.207 回答