繁体   English   中英

如何从cURL命令提取数据/结果以显示PHP输出?

[英]How do I extract data/results from a cURL command to display the output with PHP?

首先,iam在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服务器和工作网址。

我只是不知道如何制作一个有效的代码,该代码将使用PHP并使用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漂亮打印将是惊人的。

了解有关curl exec的更多信息( http://www.php.net/manual/zh/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;

    ?>

数据从curl_exec命令返回。

在另一个主题上,也许使用PHP Curl将文件上传到Zoho API,我最近在这里发布了一个包含Curl类示例的问题,将为您提供帮助。

另外,我建议您阅读PHP curl方法的手册页 ,例如curl_exec页面 -注释部分通常包含实现建议。

暂无
暂无

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

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