javascript - 使用 PHP 获取 Web 服务数据

标签 javascript php jquery web-services

如果我不能很好地解释,请原谅,我只需要一些示例、链接或您可以提供给我的任何东西来了解它是如何工作的。

我正在尝试使这个网络服务与 PHP 一起工作,我也以这个为例,它与 JS 一起工作,但是这个网络服务有一些限制,比如“我不能使用至少有不同来源的语言消费者”。

这就是例子。

$.ajax(
   {
       type:"POST",
       contentType:"application/json;charset=utf-8",
       url:"https://somewebsite.com/setsomedata",
       data:"{}",
       dataType:"json",
       async: false,
       success: function(msg) {
          a("#compInter",msg.d.data1); 
          a("#ventInter",msg.d.data2);
          a("#compAgencia",msg.d.data3);
          a("#ventAgencia",msg.d.data4);
      },
      error: function(textStatus, errorThrown, errorDetail){
          alert(errorDetail);
      }
   });

所以,问题是我不能使用 Jquery/Javascript 来使用这些数据,因为我需要使用 PHP 来完成这项工作。

所以,我认为我真的迷失在这种情况下,这就是为什么我想获得一些帮助,您可以提供任何帮助来完成这项工作。

我正在尝试用 PHP 来做这个,但我仍然遇到这个错误: [无法打开流:HTTP 请求失败! HTTP/1.1 500 内部服务器错误]

这是我的 PHP 代码:

<?php

$result = json_decode(file_get_contents('https://somewebsite.com/setsomedata'),true);
print_r($result);

?>

再次感谢您。

最佳答案

您需要使用 Curl 来使用该端点提供的数据。 file_get_contents 在某些情况下有效,但当您需要传递 header 、cookie 等时,您需要 Curl。

这是一个 Curl 类以及如何使用它的示例:

$request = new Curl($yourTargetUrlHere, [
                    'proxy' => [],
                    'headers' => [],
                ]);
$curl->go();
$response = $curl->lastRequest['response']['body']);

这是 Curl

class Curl {
/** @var _ch Curl Handler Resource */
private $_ch;

/** @var _url Url to call */
private $_url;

/* Last Response. Raw result from curl */
public $lastRequest;

/* Last Request. Formatted */
public $lastResponse;

/* Errores generated */
public $errors = array();

/** @var _params Array containing data for Methods */
private $_params;

private $_cookiesJar = array();

private $_options = array();

/* Hold the number of redirections issued by Location on go() */
private $_redirections = 0;

/* HTTP Response codes. Currently not used, but usefull to have them here
in case we need to check cURL responses */
private $_codes = array(
    100 => 'Continue',
    101 => 'Switching Protocols',
    200 => 'OK',
    201 => 'Created',
    202 => 'Accepted',
    203 => 'Non-Authoritative Information',
    204 => 'No Content',
    205 => 'Reset Content',
    206 => 'Partial Content',
    300 => 'Multiple Choices',
    301 => 'Moved Permanently',
    302 => 'Found',
    303 => 'See Other',
    304 => 'Not Modified',
    305 => 'Use Proxy',
    306 => '(Unused)',
    307 => 'Temporary Redirect',
    400 => 'Bad Request',
    401 => 'Unauthorized',
    402 => 'Payment Required',
    403 => 'Forbidden',
    404 => 'Not Found',
    405 => 'Method Not Allowed',
    406 => 'Not Acceptable',
    407 => 'Proxy Authentication Required',
    408 => 'Request Timeout',
    409 => 'Conflict',
    410 => 'Gone',
    411 => 'Length Required',
    412 => 'Precondition Failed',
    413 => 'Request Entity Too Large',
    414 => 'Request-URI Too Long',
    415 => 'Unsupported Media Type',
    416 => 'Requested Range Not Satisfiable',
    417 => 'Expectation Failed',
    500 => 'Internal Server Error',
    501 => 'Not Implemented',
    502 => 'Bad Gateway',
    503 => 'Service Unavailable',
    504 => 'Gateway Timeout',
    505 => 'HTTP Version Not Supported',
);

public function __construct($url = false, $options = array())
{
    $this->_options = $options;

    return $this->browse($url, $this->_options);
}

public function __destruct()
{
    curl_close($this->_ch);
}

/**
 * Sets cURL options
 */
private function _setOpt($flag, $value)
{
    curl_setopt($this->_ch, $flag, $value);
}

/**
 * Explodes into an array a string of colon separated cookies
 *
 * @param  string $cookies   The cookies to be exploded
 * @param  string $returnKey Return only the value for the specified key
 *
 * @return array           Associative array
 */
private function _explodeCookies($cookies, $returnKey = false)
{
    if (empty($cookies))
        return;

    $newArray = array();
    foreach (explode(';', $cookies) as $value) {
        preg_match_all('/^(.*)=(.*)$/i', $value, $c);
        if (isset($c[1][0])) {
            $newArray[trim($c[1][0])] = $c[2][0];
        }
    }

    if ($returnKey) {
        return isset($newArray[$returnKey]) ? $newArray[$returnKey] : null;
    }

    return $newArray;
}

/**
 * Implodes an array of cookies into a string of cookies
 *
 * @param  array $cookies The cookies to be imploded
 *
 * @return string          The resulting string with the cookies colon separated
 */
private function _implodeCookies($cookies)
{
    $cookieStr = '';
    foreach ((array)$cookies as $key => $value) {
        if ($key) {
            $cookieStr .= $key . '=' . $value . ';';
        }
    }

    return $cookieStr;
}

/**
 * Saves cookies to _cookieJar variable
 */
private function _saveCookies()
{
    $parsedUrl = parse_url($this->_url);

    // Save cookies (always, it doesn't matter if 'session' is true or false)
    preg_match_all('|Set-Cookie: (.*);|U', $this->lastRequest['response']['headers'], $matches);
    if (!empty($matches[1])) {
        $currentCookies                        = $this->_cookiesJar[$parsedUrl['host']];
        $newCookies                            = array_merge((array)$this->_explodeCookies($currentCookies), (array)$this->_explodeCookies(implode(';', $matches[1])));
        $this->_cookiesJar[$parsedUrl['host']] = $this->_implodeCookies($newCookies);
    }
    $_SESSION['curl_cookies'][$parsedUrl['host']] = $this->_cookiesJar[$parsedUrl['host']];
}

/**
 * Merges an array recursively. Used to merge options
 */
private function _mergeRecursive(array $array1, $array2 = null)
{
    $merged = $array1;
    if (is_array($array2)) {
        foreach ($array2 as $key => $val) {
            if (is_array($array2[$key])) {
                $merged[$key] = isset($merged[$key]) && is_array($merged[$key]) ? $this->_mergeRecursive($merged[$key], $array2[$key]) : $array2[$key];
            } else {
                $merged[$key] = $val;
            }
        }
    }

    return $merged;
}

/**
 * Prepares the connection with URL and browsing options
 */
public function browse($url = false, $options = array())
{
    if (count($options)) {
        $this->_options = $this->_mergeRecursive($this->_options, $options);
    }

    $this->_options = $this->_mergeRecursive(array(
        'ua' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0',
        'cookies' => '',
        'timeout' => 30,
        'proxy' => array(
            'ip' => '',
            'port' => '',
            'username' => '',
            'password' => '',
        ),
        'ssl' => false,
        'postdata' => array(),
        'session' => true, // should we use cookies set by previous calls?
        'referer' => '',
        'headers' => array(
            'Connection: Keep-Alive',
            'Accept-Language: en-US',
            'X-Cache:',
            'X-Cache-Lookup:',
            // 'Proxy-Authorization:', // can't set this, proxy fails authentication
            // 'Accept-Encoding: gzip', // can't set this, response doesn't get unzipped
            // 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8', // can't set this on post
        ),
        'cb' => false, // callback to manipulate the options
    ), $this->_options);

    if (is_callable($this->_options['cb'])) {
        $_fn            = $this->_options['cb'];
        $this->_options = $_fn($this->_options, $this);
    }

    // Init curl
    $this->_ch = curl_init();
    if (!empty($url)) {
        $this->_url = $url;
    }

    if (!empty($this->_url)) {
        // prepare the cookie jar
        $parsedUrl                             = parse_url($this->_url);
        $this->_cookiesJar[$parsedUrl['host']] = !empty($this->_cookiesJar[$parsedUrl['host']]) ? $this->_cookiesJar[$parsedUrl['host']] : '';
        curl_setopt($this->_ch, CURLOPT_URL, $this->_url);
    }

    curl_setopt($this->_ch, CURLOPT_USERAGENT, $this->_options['ua']);
    curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true);

    // We set this to false, to grab cookies set on the request.
    // Setting to true will cause to follow redirection but the cookies wont be stored.
    // We save cookies, parse Location, and then issue a new request to the new Location
    curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, false);

    curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, $this->_options['ssl']); // do not verify CA
    curl_setopt($this->_ch, CURLOPT_VERBOSE, true);
    curl_setopt($this->_ch, CURLOPT_HEADER, true);
    curl_setopt($this->_ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($this->_ch, CURLOPT_FRESH_CONNECT, false);
    curl_setopt($this->_ch, CURLOPT_AUTOREFERER, false);
    curl_setopt($this->_ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($this->_ch, CURLOPT_TIMEOUT, $this->_options['timeout']);

    if (!empty($this->_options['referer'])) {
        curl_setopt($this->_ch, CURLOPT_REFERER, $this->_options['referer']);
    }

    // Prepare proxy
    if (!empty($this->_options['proxy']['ip'])) {
        curl_setopt($this->_ch, CURLOPT_PROXY, $this->_options['proxy']['ip']);
        curl_setopt($this->_ch, CURLOPT_PROXYPORT, $this->_options['proxy']['port']);
        curl_setopt($this->_ch, CURLOPT_PROXYTYPE, 'HTTP');

        if (!empty($this->_options['proxy']['username'])) {
            curl_setopt($this->_ch, CURLOPT_PROXYUSERPWD, $this->_options['proxy']['username'] . ':' . $this->_options['proxy']['password']);
        }
    }

    // Prepare POST data
    if (!empty($this->_options['postdata'])) {
        $this->setPost($this->_options['postdata']);
    }

    // Prepare cookies and session
    if ($this->_options['session']) {
        @session_start();

        // pull cookies that we might have in session
        if ($this->_url && !empty($_SESSION['curl_cookies'][$parsedUrl['host']])) {
            $this->_cookiesJar[$parsedUrl['host']] = $_SESSION['curl_cookies'][$parsedUrl['host']];
        }
    }

    // Prepare headers
    curl_setopt($this->_ch, CURLOPT_HTTPHEADER, $this->_options['headers']);

    return $this;
}

/**
 * Sends the request to the specified URL
 */
public function go()
{
    if (isset($this->_params['GET'])) {
        $this->_url .= '?' . $this->_params['GET'];
    }

    // Set cokies and session info here because clearCache() can be called
    // prior sending the request
    $parsedUrl = parse_url($this->_url);
    if (!empty($this->_options['cookies'])) {
        curl_setopt($this->_ch, CURLOPT_COOKIE, $this->_options['cookies']);
    } elseif ($this->_url && $this->_options['session'] && !empty($this->_cookiesJar[$parsedUrl['host']])) {
        curl_setopt($this->_ch, CURLOPT_COOKIE, $this->_cookiesJar[$parsedUrl['host']]);
    }

    try {
        $this->lastResponse = curl_exec($this->_ch);
    } catch (Exception $e) {
        $this->errors[] = $e->getMessage();

        return false;
    }

    $headerSent = curl_getinfo($this->_ch, CURLINFO_HEADER_OUT);

    // Get the headers
    $parts = explode("\r\n\r\nHTTP/", $this->lastResponse);
    $parts = (count($parts) > 1 ? 'HTTP/' : '') . array_pop($parts);
    @list($responseHeader, $responseBody) = explode("\r\n\r\n", $parts, 2);

    preg_match_all('/^Location:(.*)$/mi', $this->lastResponse, $matches);
    $location = '';
    if (!empty($matches[1])) {
        $location = trim($matches[1][0]);
    }

    // Put request in the structure
    $this->lastRequest = array(
        'request' => array(
            'headers' => curl_getinfo($this->_ch, CURLINFO_HEADER_OUT),
            'url' => $this->_url,
            'proxy' => !empty($this->_options['proxy']['ip']) ? implode(':', $this->_options['proxy']) : '',
            'body' => !empty($this->_options['postdata']) ? $this->_options['postdata'] : '',
        ),
        'response' => array(
            'headers' => $responseHeader,
            'time' => curl_getinfo($this->_ch, CURLINFO_TOTAL_TIME),
            'location' => $location,
            'info' => curl_getinfo($this->_ch),
            'body' => $responseBody,
        ),
    );
    $this->_saveCookies();

    // Follow new location redirect
    if ($this->_redirections > 10) {
        die('Loop redirection');
    }

    if (!empty($this->lastRequest['response']['location'])) {
        $this->_redirections++;
        $this->browse($this->lastRequest['response']['location'])->go();
    } else {
        $this->_redirections = 0;
    }

    return $this->lastRequest;
}

/**
 * Destroys session and clears cookies.
 */
public function clearCache()
{
    @session_destroy();
    $parsedUrl                             = parse_url($this->_url);
    $this->_cookiesJar[$parsedUrl['host']] = '';
}

/**
 * Sets the POST params to be sent
 */
public function setPost($params)
{
    $this->_params['POST'] = $params;
    curl_setopt($this->_ch, CURLOPT_POST, true);
    curl_setopt($this->_ch, CURLOPT_POSTFIELDS, is_array($this->_params['POST']) ? http_build_query($this->_params['POST']) : $this->_params['POST']);
}

/**
 * Sets the GET params to be sent
 */
public function setGet($params)
{
    $this->_params['GET'] = http_build_query($params);
}

public function getCookie($key)
{
    $parsedUrl = parse_url($this->_url);

    return $this->_explodeCookies($this->_cookiesJar[$parsedUrl['host']], $key);
}

public function debug()
{
    $this->lastRequest['response']['body'] = htmlspecialchars($this->lastRequest['response']['body'], ENT_QUOTES, 'UTF-8');
    echo '<pre>' . print_r($this->lastRequest, 1) . '</pre>';
    die();
}
}

关于javascript - 使用 PHP 获取 Web 服务数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39400331/

相关文章:

javascript - 如何使用闭包创建 javascript 库

php - 如何突出显示一个文本段落与另一个文本段落的变化/差异?

php - 让 Varnish 在 Magento 上工作

javascript - jQuery:如何从 url/hash 获取热链接?

javascript - 使用 jQuery 将 JS 对象转换为数组

javascript - 如何在基于JS的聊天室中查找用户的IP?

javascript - Angular js http 获取失败

php - sql 计算查询不运行,#1054 字段列表中的未知列

php - 使用 RegEx 将抓取限制为 X 个字符 + 其他规范

jquery - Google Maps API v3、jQuery UI 选项卡、 map 未调整大小