public function _send_and_receive($url, $method, $data = array(), $start_tag = false)
{
$params = '';
$el = $start_tag ? $start_tag : $this->element_name;
// Singular this time
if ($this->request_format == 'url') {
foreach ($data as $k => $v) {
if ($k != 'id' && $k != 'created-at' && $k != 'updated-at') {
$params .= '&' . $el . '[' . str_replace('-', '_', $k) . ']=' . rawurlencode($v);
}
}
$params = substr($params, 1);
} elseif ($this->request_format == 'xml') {
$params = '<?xml version="1.0" encoding="UTF-8"?><' . $el . ">\n";
foreach ($data as $k => $v) {
if ($k != 'id' && $k != 'created-at' && $k != 'updated-at') {
$params .= $this->_build_xml($k, $v);
}
}
$params .= '</' . $el . '>';
}
if ($this->extra_params !== false) {
$url = $url . $this->extra_params;
}
$this->request_body = $params;
$this->request_uri = $url;
$this->request_method = $method;
$res = $this->_fetch($url, $method, $params);
if ($res === false) {
return $this;
}
// Keep splitting off any top headers until we get to the (XML) body:
while (strpos($res, "HTTP/") === 0) {
list($headers, $res) = explode("\r\n\r\n", $res, 2);
$this->response_headers = $headers;
$this->response_body = $res;
if (preg_match('/HTTP\\/[0-9]\\.[0-9] ([0-9]+)/', $headers, $regs)) {
$this->response_code = $regs[1];
} else {
$this->response_code = false;
}
if (!$res) {
return $this;
} elseif ($res == ' ') {
$this->error = 'Empty reply';
return $this;
}
}
// parse XML response
$xml = new SimpleXMLElement($res);
// normalize xml element name in case rails ressource contains an underscore
if (str_replace('-', '_', $xml->getName()) == $this->element_name_plural) {
// multiple
$res = array();
$cls = get_class($this);
foreach ($xml->children() as $child) {
$obj = new $cls();
foreach ((array) $child as $k => $v) {
$k = str_replace('-', '_', $k);
if (isset($v['nil']) && $v['nil'] == 'true') {
continue;
} else {
$obj->_data[$k] = $v;
}
}
$res[] = $obj;
}
return $res;
} elseif ($xml->getName() == 'errors') {
// parse error message
$this->error = $xml->error;
$this->errno = $this->response_code;
return false;
}
foreach ((array) $xml as $k => $v) {
$k = str_replace('-', '_', $k);
if (isset($v['nil']) && $v['nil'] == 'true') {
continue;
} else {
$this->_data[$k] = $v;
}
}
return $this;
}