How to convert this cURL to wp_remote_*?


My function below includes a cURL call which throws a text string at a Google Cloud text analysis API, returning a response object, which we then parse to get a specific piece.

It has been recommended to me that I switch the cURL PHP statement to use WordPress’ wp_remote_get.

I have read the docs for that but, to be honest, I don’t understand how my cURL header fields should map to wp_remote_get arguments. Or even if it should be wp_remote_post rather than wp_remote_get.

How can I try and understand what to do here?

    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 = '{
        $payload = $data;

        // Call the API endpoint, with API key
        $url = ''.$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

        // Pluck out the first value from the response object
        $ent_val = $arr['entities'][0][$entity];

        return $ent_val;
        // List of possible entities:
        // UNKNOWN
        // PERSON
        // LOCATION
        // EVENT
        // WORK_OF_ART
        // CONSUMER_GOOD
        // OTHER

Robert Andrews 2 months 0 Answers 14 views 0

Leave an answer