【问题标题】:How do I extract data/results from a cURL command to display the output with PHP?如何从 cURL 命令中提取数据/结果以使用 PHP 显示输出?
【发布时间】:2014-05-14 10:03:21
【问题描述】:

首先,我对 PHP 和 cURL 都很陌生

来自命令:

curl -i 'http://xxx:xxx/v2.0/tokens' -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"auth": {"tenantName": "xxx", "passwordCredentials": {"username": "admin", "password": "xxx"}}}'

我想使用 POST/GET 和 PHP 生成此命令的结果。我有一个 apache 服务器和工作 url。

我只是不知道如何制作一个可以使用 PHP 获取代码并生成输出到空页面的工作代码。

我一直在搜索示例,我知道您必须使用以下一些:

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, '');
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_exec($ch);

curl_close($ch);
?>

我只是不知道如何将 cURL 命令中的正确标志附加到 PHP 代码,可能还遗漏了一些重要的东西来包装代码。

在此先感谢,如果我不能很好地解释我的问题,我们深表歉意。

** ***编辑:* ****

所以我编写了一个代码,它可以满足我的需要,它从 PHP 页面上的 cURL 命令生成原始结果。 代码如下:

<?php
$request_body = '{"auth": {"tenantName": "xxx", "passwordCredentials": {"username": "admin", "password": "xxx"}}}';
$ch = curl_init('http://xxx:xxx/v2.0/tokens');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_HEADER, true); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        $response = curl_exec($ch);
var_dump($response);
?>

现在的问题是,如果我可以操纵输出以更好的方式显示,现在它只是一个大字符串,某种形式的 JSON 漂亮打印会很棒。

【问题讨论】:

    标签: php post curl get


    【解决方案1】:

    阅读有关 curl exec 的更多信息 (http://www.php.net/manual/en/function.curl-exec.php)

    <?php
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_URL, "");
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, '');
        curl_setopt($ch, CURLOPT_POSTFIELDS, '');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        $data = curl_exec($ch);
    
        curl_close($ch); 
    print $data;
    
        ?>
    

    【讨论】:

    • 感谢您的回复。
    【解决方案2】:

    数据从 curl_exec 命令返回。

    虽然关于不同的主题,可能是Uploading files to Zoho API with PHP Curl,但我最近在这里发布的一个问题包含一个 Curl 类示例,将对您有所帮助。

    此外,我建议您阅读 manual pages 以了解 PHP curl 方法,例如curl_exec page - cmets 部分通常包含实施建议。

    【讨论】:

    • 谢谢你的回复,我去看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    相关资源
    最近更新 更多