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

时间:2014-06-04 08:42:37

标签: php arrays variables curl url-parameters

我有这个PHP代码使用cURL解析来自Indeed.com的xml提要。我将服务器信息(例如REMOTE_ADDR和HTTP_USER_AGENT)传递到url的参数中,但它们没有被传递。

检查以下代码的这一部分。 '.geoCheckIP($_SERVER['REMOTE_ADDR']).'

这是正确的方法。在CURLOPT_URL =>中,当它是数组的一部分时,不确定它是否是正确的方法。

在cURL中使用数组时,将这些服务器片段传递到url参数的正确方法是什么,如CURLOPT_URL =>中的以下函数?

下面的php代码是我页面上的完整代码,因此您可以更好地了解正在发生的事情。

我试图检测用户城市,说明他们到达我的网站以显示他们当地的工作列表。 php代码有效,我可以在网页上回显城市状态,但它不会将相同的信息传递给数组中的curl_request()函数。请帮忙。

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

功能调用

这是在正文中调用函数的方式

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

什么有用

只有从CURLOPT_URL

中删除变量时,上面的代码才有效

此作品

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',

这不起作用

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',

3 个答案:

答案 0 :(得分:1)

此处不需要使用cURL,加载速度非常慢。这是一个非常简单的方法来获取纯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';

然后,您在下面看到的其余代码将会显示在您希望输出显示的页面的<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 -->

答案 1 :(得分:0)

这里有一个正确的解释: passing arrays as url parameter

您可以从那里获取语法并将其与curl一起使用!

一个函数示例,它可以帮助您以数组形式创建url-param:

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

之后你只需拿走你的网址并将其与结果连接起来:

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

答案 2 :(得分:0)

像这样;

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

修改 可能有1个,可能有2个原因导致这不适合你;

1。你没有传递你在函数外定义的变量(我的第一个答案中也没有)。 要解决这个问题,您需要在函数定义中将它们传递给function curl_request($user_ip, $user_agent, $user_location),并在调用函数时传递它们。或者更改您在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是一个全局变量,所以它不需要作为参数传递给函数就可以这样工作。

2。您的通话api仅接受POST请求GET,在这种情况下,我的第一个示例无效,您的第一个示例应该可以正常工作通过点 1

中列出的变量