Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从用户名Instagram获取用户ID_Php_Jquery_Json_Instagram - Fatal编程技术网

Php 从用户名Instagram获取用户ID

Php 从用户名Instagram获取用户ID,php,jquery,json,instagram,Php,Jquery,Json,Instagram,我想知道如何使用Instagram API从用户名中获取用户ID,但我运气不好 到目前为止,我的代码是: $username = 'some user name'; $username = strtolower($username); // sanitization $token = "ACCESS_TOKEN_HERE"; $url = "https://api.instagram.com/v1/users/search?q=".$username."&access_token=".$

我想知道如何使用Instagram API从用户名中获取用户ID,但我运气不好

到目前为止,我的代码是:

$username = 'some user name';
$username = strtolower($username); // sanitization
$token = "ACCESS_TOKEN_HERE";
$url = "https://api.instagram.com/v1/users/search?q=".$username."&access_token=".$token;
$get = file_get_contents($url);
$json = json_decode($get);

foreach($json->data as $user)
{
    if($user->username == $username)
    {
        return $user->id;
    }
}

使用评论中的建议,我能够使用此代码从username获取userid。请让我知道,因为我不是最伟大的PHP开发人员,也许有一种更简洁的方法可以做到这一点

$user = USER_NAME;
$count = NUMBER_TO_RETURN;
$token = ACCESS_TOKEN_HERE;

$query = http_build_query(
                array(
                    'q'=>$user,
                    'count'=>$count,
                    'access_token'=>$token

                )
            );  
    $url = "https://api.instagram.com/v1/users/search?{$query}";

    // Gets our data
    function fetchData($url){
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_TIMEOUT, 20);
         $result = curl_exec($ch);
         curl_close($ch); 
         return $result;
    }

    // Pulls and parses data.
    $result = fetchData($url);
    $result = json_decode($result);
    $userid = $result->data[0]->id;
echo $userid;
将用户名放在“”中,例如:


对我来说很好

您需要对
$username
进行URL编码吗?请注意,空格将打断
$url
。尝试在
$url
周围使用
rawurlencode()
,什么不起作用?您是否在
$get
中获取任何数据?您可以回显它吗?尝试使用
http\u build\u query
来生成查询字符串<代码>$query=http_构建_查询(数组('username'=>$username,'access_token'=>$token))$url=”https://api.instagram.com/v1/users/search?{$query}”好的,伙计们。。知道了!!谢谢大家!!这种方法不适用于短用户名。例如,对于这个用户-,您将得到所有类型的用户,这些用户都匹配“mus”-“musiemu”,“musclekingz”,“mustafaseven”,等等。