如何使用IBM Watson的Curl获取json响应

时间:2018-02-11 08:33:40

标签: php html json curl watson

我正在尝试编写一个简单的Web应用程序,该应用程序调用IBM Watson NLC api来对用户将输入到文本框的文本进行分类。

我已经创建了以下内容,如果输入单个单词并且在给出句子失败时它可以工作。怎么了?任何帮助。

输入语言将是阿拉伯语。

文件1 - NLCApp.php

<form action="post-method.php" method="POST">

<input type="text" name="texta" placeholder="Text to Query" multiple />

<input type="submit" name="submit" />

</form> 

文件2 - Postmethod.php

<?php

    $wtext= ($_POST['texta']);
    //echo $wtext;

    $url = "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/{My Classifier ID}/classify?text=$wtext";

    $headers = array('Content-Type:application/json');

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_USERPWD, '{My Classifier Username:My Classifier Password}');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_args));

    $result = curl_exec($ch);

    if ($result === FALSE) {die('Send Error: ' . curl_error($ch)); }
    curl_close($ch);

    echo $result;

?>

我很喜欢编码,大部分这些小代码都是从stackoverflow和其他帮助论坛中的多个用户帖子中复制粘贴的。

有关完成此任务的任何帮助。

1 个答案:

答案 0 :(得分:0)

请试试这个:

  1. $ch = curl_init($url);
  2. 删除未使用的标题
  3. 添加错误处理
  4. <?php
    
    $wtext= ($_POST['texta']);
    echo "Passed text: ".$wtext; 
    
    $url  = "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/{My Classifier ID}/classify?text=";
    $url .= urlencode($wtext);
    
    // $headers = array('Content-Type:application/json');
    
    $ch = curl_init($url);
    
    curl_setopt($ch, CURLOPT_USERPWD, '{My Classifier Username:My Classifier Password}');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // curl_setopt($ch, CURLOPT_URL, $url);
    // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    //curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_args));
    
    $result = curl_exec ($ch);
    // also get the error and response code
    $errors = curl_error($ch);
    $response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    curl_close($ch);
    
    var_dump($result);
    var_dump($errors);
    var_dump($response);
    
    ?>