How can one determine if data is already encoded in utf8 before applying utf8_encode?

To determine if data is already encoded in utf8 before applying utf8_encode, you can use the mb_detect_encoding function in PHP. This function can detect the current encoding of a string and return it. If the detected encoding is already utf8, then there is no need to apply utf8_encode.

$data = "Some data to check";

if(mb_detect_encoding($data, 'UTF-8', true) !== 'UTF-8') {
    $data = utf8_encode($data);
}

// Continue with processing the data