Help Modifying Generic REST Helper PHP Example Code to Support XML DOM

Posted by Jennifer Baker on Stack Overflow See other posts from Stack Overflow or by Jennifer Baker
Published on 2010-06-01T20:40:58Z Indexed on 2010/06/01 20:43 UTC
Read the original article Hit count: 307

Filed under:
|
|

Hi!

I found this example PHP source code at HTTP POST from PHP, without cURL

I need some help modifying the example PHP source to support XML DOM for manipulating a REST API.

I thought that if I update the CASE statement for the XML section below from

$r = simplexml_load_string($res);

to

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

that it would work but it doesn't. :(

Any help would be appreciated.

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;
}

© Stack Overflow or respective owner

Related posts about php

Related posts about http