在php中将字符串转换为utf-8

There is a script written in Java and I am trying to convert it into PHP, but I'm not getting the same output.

How can I get it in PHP same as in Java?

Script written in Java

String key = "hghBGJH/gjhgRGB+rfr4654FeVw12y86GHJGHbnhgnh+J+15F56H";

byte[] kSecret = ("AWS4" + key).getBytes("UTF8");

Output: [B@167cf4d

Script written in PHP

$secret_key = "hghBGJH/gjhgRGB+rfr4654FeVw12y86GHJGHbnhgnh+J+15F56H";
utf8_encode("AWS4".$secret_key);

Output: AWS4hghBGJH/gjhgRGB+rfr4654FeVw12y86GHJGHbnhgnh+J+15F56H

You can't sysout an byte array without converting it to a string, UTF-8 by default, toString() is being called,when you do something like:

System.out.println("Weird output: " + byteArray);

This will output the garbage you mentioned above. Instead, create a new instance of the standard String class.

System.out.println("UTF-8: " + new String(byteArray));

In Java you get the object reference of the byte array, not its value. Try:

new String(kSecret, "UTF-8");

The result [B@167cf4d you are getting is a toString() call on the byte array. The [B means the value is a byte array. @167cf4d is it's location within the virtual memory. You simply cannot get the PHP script to give you the same result. What you need to do is fix the printing on the Java side, but we don't know what API you're using to print it and where. Is it a web-application, a local application, etc... ?

edit:
Since you're using it in a Java web-application, there are two likely scenarios. The code is either in a Servlet, or in a JSP. If it's in a servlet, you have to set your output to UTF-8, then you can simply print the string like so:

        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.write("AWS4");
        out.write(key);

If it's in a JSP, that makes it a bit more inconvenient, because you have to make sure you don't leave white-spaces like new lines before the printing begins. It's not a problem for regular HTML pages, but it's a problem if you need precisely formatted output to the last byte. The response and out objects exist readily there. You will likely have some <%@page tags with attributes there, so you have to make sure you're opening the next one as you're closing the last. Also a new line on the end of file could skew the result, so in general, JSP is not recommended for white-space-sensitive data output.