【问题标题】:How can I get Github release's tag_name via PHP?如何通过 PHP 获取 Github 版本的 tag_name?
【发布时间】:2018-08-24 04:36:16
【问题描述】:

我曾尝试使用 php 来获取 Github 版本的 tag_name,但徒劳无功。 链接是Latest Release

<?php 

ini_set('user_agent', 'Mozilla/4.0 (compatible; MSIE 6.0)');
 $json =file_get_contents("https://api.github.com/repos/carry0987/Messageboard/releases/latest") ;
 $myArray = json_decode($json);
 foreach( $myArray as $key => $value ){
     echo $key."\t=>\t".$value."\n";
 }
?>

【问题讨论】:

  • 您正在拉回一个对象,请尝试将第二个 json_decode 参数设置为 true 以将其作为数组返回。
  • @JonStirling 喜欢这样吗? json_decode($json,true);
  • 是的,就是这样。
  • 为什么不用$myArray-&gt;tag_name 为什么人们那么害怕物体。也许将$myArray 重命名为$myObj 更准确
  • @RiggsFolly 我是 php 新手...我将重新编辑我的代码,让它变得更好

标签: php github


【解决方案1】:

这似乎对我有用。我必须设置一个流上下文才能让它工作

<?php

$url = "https://api.github.com/repos/carry0987/Messageboard/releases/latest";
$opts = [
        'http' => [
                'method' => 'GET',
                'header' => [
                        'User-Agent: PHP'
                ]
        ]
];

$ctx = stream_context_create($opts);
$json = file_get_contents( $url, 0, $ctx );

$myObj = json_decode($json);

echo 'The tag name is ' . $myObj->tag_name;

结果:

The tag name is 1.0.4

编辑:

然后回到你的原始代码,这也有效

<?php
ini_set('user_agent', 'Mozilla/4.0 (compatible; MSIE 6.0)');

$json = file_get_contents("https://api.github.com/repos/carry0987/Messageboard/releases/latest") ;

$myObj = json_decode($json);

echo 'The tag name is ' . $myObj->tag_name;

【讨论】:

  • 您使用哪个版本的 PHP?我尝试了您的代码,但仍然无法正常工作,我使用的是 PHP 7.0.6,而我的服务器是虚拟主机..
  • 我使用的是 7.0.23,但让我检查一下 7.0.6
  • 使用对象表示法,即在我的编辑代码中
  • 我认为这是我的服务器的问题...我仍然收到 504 错误,我可以看看你的测试网站吗?
  • 我实际上是在我的 Windows PC 上从 PHP CLI 运行的,没有涉及任何网站
【解决方案2】:

尝试延长超时时间

<?php 
ini_set('user_agent', 'Mozilla/4.0 (compatible; MSIE 6.0)');
ini_set('max_execution_time', 300);
 $json =file_get_contents("https://api.github.com/repos/carry0987/Messageboard/releases/latest") ;
 //get a json not an array
 $myArray = json_decode($json,true);
 foreach( $myArray as $key => $value ){
     echo $key."\t=>\t".$value."\n";
 }
?>

【讨论】:

    猜你喜欢
    • 2018-08-23
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多