简体   繁体   English

如何将变量作为 cURL 数组中的 url 参数传递给 CURLOPT_URL

[英]How do I pass variables as url parameters in cURL array to CURLOPT_URL

I have this php code using cURL to parse an xml feed from Indeed.com.我有这个 php 代码使用 cURL 解析来自 Indeed.com 的 xml 提要。 I'm passing server information such as REMOTE_ADDR and HTTP_USER_AGENT into the parameters of the url but they are not being passed.我将 REMOTE_ADDR 和 HTTP_USER_AGENT 等服务器信息传递到 url 的参数中,但它们没有被传递。

Check this part of the code below.检查下面的这部分代码。 '.geoCheckIP($_SERVER['REMOTE_ADDR']).'

This is the correct way to do it.这是正确的做法。 Just not sure if it is the correct way to do it when it is part of an array in CURLOPT_URL =>只是不确定当它是 CURLOPT_URL => 中数组的一部分时它是否是正确的方法

What is the proper way to pass these server snippets into the url parameters when using an array in cURL like in the below function in CURLOPT_URL =>?在 cURL 中使用数组时,将这些服务器片段传递到 url 参数的正确方法是什么,如下面的 CURLOPT_URL => 中的 function 所示?

The below php code is the entire code on my page so you can get a better idea of what is going on.以下 php 代码是我页面上的完整代码,因此您可以更好地了解发生了什么。

I'm trying to detect the users city, state when they arrive at my site to display job listings in their local area.我正在尝试检测用户城市 state 何时到达我的站点以在其本地显示职位列表。 The php code works and I can echo the city state on the web page, but it is just not passing that same info to the function curl_request() in the array. php 代码有效,我可以在 web 页面上回显城市 state,但它只是没有将相同的信息传递给数组中的 function curl_request()。 Please help.请帮忙。

<?php
// Convert IP into city state country (Geo Location function)
function geoCheckIP($ip){
if(!filter_var($ip, FILTER_VALIDATE_IP))
{
throw new InvalidArgumentException("IP is not valid");
}

$response=@file_get_contents('http://www.netip.de/search?query='.$ip);
if (empty($response))
{
throw new InvalidArgumentException("Error contacting Geo-IP-Server");
}

$patterns=array();
$patterns["domain"] = '#Domain: (.*?)&nbsp;#i';
$patterns["country"] = '#Country: (.*?)&nbsp;#i';
$patterns["state"] = '#State/Region: (.*?)<br#i';
$patterns["town"] = '#City: (.*?)<br#i';

$ipInfo=array();

foreach ($patterns as $key => $pattern)
{

$ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
}
/*I've included the substr function for Country to exclude the abbreviation (UK, US, etc..)
To use the country abbreviation, simply modify the substr statement to:
substr($ipInfo["country"], 0, 3)
*/
$ipdata = $ipInfo["town"]. ", ".$ipInfo["state"]/*.", ".substr($ipInfo["country"], 4)*/;
return $ipdata;
}


// Indeed php function
function curl_request(){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://api.indeed.com/ads/apisearch?publisher=&q=computer+repair&l='.geoCheckIP($_SERVER['REMOTE_ADDR']).'&sort=&radius=25&st=&jt=&start=&limit=&fromage=&highlight=1&filter=1&latlong=0&co=us&chnl=computer+help+wanted&userip='.$_SERVER['REMOTE_ADDR'].'&useragent='.$_SERVER['HTTP_USER_AGENT'].'&v=2',
));
$resp = curl_exec($curl);
curl_close($curl);
return $resp;
}

function xmlToArray($input, $callback = null, $recurse = false) {
$data = ((!$recurse) && is_string($input))? simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA): $input;
if ($data instanceof SimpleXMLElement) $data = (array) $data;
if (is_array($data)) foreach ($data as &$item) $item = xmlToArray($item, $callback, true);
return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
}
?>

FUNCTION CALL FUNCTION 致电

This is how the function is called in the body这就是 function 在正文中的调用方式

    <ol>
  <?php

for($i=0;$i<10;$i++){    // using for loop to show number of  jobs

$resp=curl_request($i);

$arrXml = xmlToArray($resp);

$results=$arrXml['results'];

?>
  <li>
    <p><strong>Job :</strong> <a href="<?php echo $results['result'][$i]['url']; ?>" target="_blank"><?php echo $results['result'][$i]['jobtitle']; ?></a></p>
    <p><strong>Company:</strong> <?php echo $results['result'][$i]['company']; ?></p>
    <p><strong>Location:</strong> <?php echo $results['result'][$i]['formattedLocationFull']; ?></p>
    <p><strong>Date Posted :</strong> <?php echo $results['result'][$i]['formattedRelativeTime'];?> on <?php echo $results['result'][$i]['date'];?></p>
    <p><strong>Description :</strong> <?php echo $results['result'][$i]['snippet']; ?></p>
  </li>
  <?php } ?>
</ol>

What works什么有效

This code above works only if I remove the variables from the CURLOPT_URL上面的代码只有在我从 CURLOPT_URL 中删除变量时才有效

This works这有效

CURLOPT_URL => 'http://api.indeed.com/ads/apisearch?publisher=&q=computer+repair&l=city,state&sort=&radius=25&st=&jt=&start=&limit=&fromage=&highlight=1&filter=1&latlong=0&co=us&chnl=computer+help+wanted&userip=111.111.111.111&useragent=mozila&v=2',

This does not work这不起作用

CURLOPT_URL => 'http://api.indeed.com/ads/apisearch?publisher=&q=computer+repair&l='.geoCheckIP($_SERVER['REMOTE_ADDR']).'&sort=&radius=25&st=&jt=&start=&limit=&fromage=&highlight=1&filter=1&latlong=0&co=us&chnl=computer+help+wanted&userip='.$_SERVER['REMOTE_ADDR'].'&useragent='.$_SERVER['HTTP_USER_AGENT'].'&v=2',

Using cURL is not needed for this and was loading very slow. 此时不需要使用cURL,加载速度非常慢。 Here is a very simple way to get the results of the xml document in pure php with the geoCheckIP function fully working with it. 这是一个非常简单的方法来获取纯PHP中的xml文档的结果,geoCheckIP函数完全使用它。

<?php

// Convert IP into city state country (Geo Location function)
function geoCheckIP($ip){
    if(!filter_var($ip, FILTER_VALIDATE_IP))
    {
    throw new InvalidArgumentException('IP is not valid');
    }

    $response=@file_get_contents('http://www.netip.de/search?query='.$ip);
    if (empty($response))
    {
    throw new InvalidArgumentException('Error contacting Geo-IP-Server');
    }

    $patterns=array();
    $patterns["domain"] = '#Domain: (.*?)&nbsp;#i';
    $patterns["country"] = '#Country: (.*?)&nbsp;#i';
    $patterns["state"] = '#State/Region: (.*?)<br#i';
    $patterns["town"] = '#City: (.*?)<br#i';

    $ipInfo=array();

    foreach ($patterns as $key => $pattern)
    {

    $ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
    }
    /*I've included the substr function for Country to exclude the abbreviation (UK, US, etc..)
    To use the country abbreviation, simply modify the substr statement to:
    substr($ipInfo["country"], 0, 3)
    */
    $ipdata = $ipInfo["town"]. ", ".$ipInfo["state"]/*.", ".substr($ipInfo["country"], 4)*/;
    return $ipdata;
}


// Indeed.com API URL parameters
$url = 'http://api.indeed.com/ads/apisearch'.'?';
$publisher = 'YOUR PUB NUMBER GOES HERE';
$q = 'title:(java or java+programmer or java+programming)';
$l = geoCheckIP($_SERVER['REMOTE_ADDR']);
$sort = 'date';
$radius = '20';
$st = '';
$jt = '';
$start = '0';
$limit = '25';
$fromage = '';
$highlight = '0';
$filter = '1';
$latlong = '0';
$co = 'us';
$chnl = 'YOUR CHANNEL NAME';
$userip = $_SERVER['REMOTE_ADDR'];
$useragent = isset($_SERVER['HTTP_USER_AGENT']) ? ($_SERVER['HTTP_USER_AGENT']) : 'unknown';
$v = '2';

Then the rest of the code you see below will go below the <body> tag of your page where you want the output to show up at. 然后,您在下面看到的其余代码将位于您希望输出显示的页面的<body>标记下方。

    <!-- BEGIN INDEED ORDERED LIST-->
    <ol class="jobs">
      <?php

    $xml = simplexml_load_file($url."publisher=".$publisher."&q=".$q."&l=".$l."&sort=".$sort."&radius=".$radius."&st=".$st."&jt=".$jt."&start=".$start."&limit=".$limit."&fromage=".$fromage."&highlight=".$highlight."&filter=".$filter."&latlong=".$latlong."&co=".$co."&chnl=".$chnl."&userip=".$userip."&useragent=".$useragent."&v=".$v);

    foreach($xml->results->result as $result) { ?>
      <li class="job">
        <div id="jobtitle"><strong><a onmousedown="<?php echo $result->onmousedown;?>" rel="nofollow" href="<?php echo $result->url;?>" target="_blank"><?php echo $result->jobtitle;?></a></strong></div>
        <div id="company"><?php echo $result->company;?></div>
        <div id="snippet">
          <?php echo $result->snippet;?>
        </div>
        <div id="location"><strong>Location:</strong> <?php echo $result->formattedLocationFull;?></div>
        <div id="date"><span class="posted">Posted <?php echo $result->formattedRelativeTime;?></span></div>
      </li>
      <?php } ?>
    </ol>
    <!-- END INDEED ORDERED LIST -->

There is a proper explanation here: passing arrays as url parameter 这里有一个正确的解释: 将数组作为url参数传递

You can just take the syntax from there and use it with curl! 您可以从那里获取语法并将其与curl一起使用!

example for a function which should help you create a url-param in array-form: 一个函数的示例,它可以帮助您创建数组形式的url-param:

public function createArrParam($key, $values) {
    return implode('&amp;' . $key . '[]=', array_map('urlencode', $values));
}

after that you just take your url and concatenate it with the result: 之后,您只需将您的网址与结果连接起来:

$values = array(1, 2, 3, 4, 5);
$url = 'http://stackoverflow.com?bla=blupp' . createArrParam('myArr', $values);

Like so; 像这样;

function curl_request()
{
    // Get cURL resource
    $curl = curl_init();
    // Set some options
    $curl_config = array(
        CURLOPT_URL => 'http://api.indeed.com/ads/apisearch',
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_POSTFIELDS => array(
            "publisher" => "",
            "q" => "computer+repair",
            "l" => $user_location,
            "sort" => "",
            "radius" => 25,
            "st" => "",
            "jt" => "",
            "start" => "",
            "limit" => "",
            "fromage" => "",
            "highlight" => 1,
            "filter" => 1,
            "latlong" => 0,
            "co" => "us",
            "chnl" => "computer+help+wanted",
            "userip" => $user_ip,
            "useragent" => $user_agent,
            "v" => 2
        )
    );
    curl_setopt_array($curl, $curl_config);
    // Send the request & save response to $resp
    $resp = curl_exec($curl);
    // Close request to clear up some resources
    curl_close($curl);
    return $resp;
}

EDIT There may be 1, possibly 2 reasons why this isn't working for you; 编辑可能有1个,可能有2个原因,为什么这不适合你;

1. your not passing in the variables you've defined outside the function (neither did I in my first answer). 1.你没有传入你在函数之外定义的变量(在我的第一个答案中也没有)。 To fix this you either need to pass them in like so function curl_request($user_ip, $user_agent, $user_location) in your function definition and as well when calling the function. 要解决这个问题,您需要在函数定义中调用function curl_request($user_ip, $user_agent, $user_location)以及调用函数时传递它们。 Or change how you enter them in the URL string; 或者更改在URL字符串中输入的方式;

curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://api.indeed.com/ads/apisearch?publisher=&q=computer+repair&l='.geoCheckIP($_SERVER['HTTP_USER_AGENT']).'&sort=&radius=25&st=&jt=&start=&limit=&fromage=&highlight=1&filter=1&latlong=0&co=us&chnl=computer+help+wanted&userip='.$$_SERVER['REMOTE_ADDR'].'&useragent='.$_SERVER['HTTP_USER_AGENT'].'&v=2'
));

$_SERVER is a global variable so it does not need passing into the function as a parameter to work like this. $_SERVER是一个全局变量,因此它不需要作为参数传递给函数,就像这样工作。

2. The api your calling does not accept POST requests only GET in which case my first example wont work, and your first example should work, once you pass through the variables as outlined in point 1. 2. api你的调用不接受POST请求只有GET在这种情况下我的第一个例子不会工作,你的第一个例子应该工作,一旦你通过变量,如第1点所述

 $url = 'https://localhost/host/wp-json/wc/v3';
 $consumer_key = 'ck_63dbe94df1343';
 $consumer_secret = 'cs_120aa6787d';
 $collection_name = 'customers';
 $request_url = $url . '/' . $collection_name . '?consumer_Key=' . $consumer_key . '&consumer_secret=' . $consumer_secret;

 $curl = curl_init($request_url);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM