我下面的函数包括一个cURL调用,该调用向Google云文本分析API抛出一个文本字符串,返回一个响应对象,然后对其进行解析以获得特定片段。
建议我将cURL-PHP语句切换为使用WordPress\'wp_remote_get
.
我已经阅读了docs 但是,老实说,我不知道我的cURL头字段应该如何映射到wp_remote_get
参数。或者即使应该wp_remote_post
而不是wp_remote_get
.
我怎样才能试着理解在这里该做什么?
function get_entity_type(
$text_to_analyse, // passed string to be handed to GCloud NLP
$entity = \'type\' // part of each "entities" result to return
) {
// Google Cloud API key
$options = get_option( \'cxt_settings\' );
$google_nlp_api = $options[\'cxt_gcloud\'];
// Supply data payload in JSON format
$data = \'{
"document":{
"type":"PLAIN_TEXT",
"content":"\'.$text_to_analyse.\'"
},
"encodingType":"UTF8"
}\';
$payload = $data;
// Call the API endpoint, with API key
$url = \'https://language.googleapis.com/v1/documents:analyzeEntities?key=\'.$google_nlp_api;
// Prepare to get results using cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
\'Content-Type: application/json\',
\'Content-Length: \' . strlen($payload))
);
// Submit the POST request
$result = curl_exec($ch);
// Store result in array
$arr = json_decode($result, true);
// Close cURL session handle
curl_close($ch);
// Pluck out the first value from the response object
$ent_val = $arr[\'entities\'][0][$entity];
return $ent_val;
// List of possible entities: https://cloud.google.com/natural-language/docs/reference/rest/v1/Entity#Type
// UNKNOWN
// PERSON
// LOCATION
// ORGANIZATION
// EVENT
// WORK_OF_ART
// CONSUMER_GOOD
// OTHER
}