Search code examples
phparraysjsonlatin1

encode json array from latin1


So i am very new to php and having problem with my array.

"Basically I have an array with 5 fields. Now the data is partially in latin1-german. But this let's the php output "null". How do I decode the array, that makes the php return the right text?"

edit: So I altered the code (JSON_PRETTY_PRINT made it return nothing). But the problem still remains. The special characters like "ä" and "ü" still make it return ":null".

// get all products from products table
$result = mysql_query("SELECT *FROM silberhell_app") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $product = array();
    $product["pid"] = $row["pid"];
    $product["name"] = $row["name"];
    $product["kategorie"] = $row["kategorie"];
    $product["beschreibung"] = $row["beschreibung"];
$product["bild"] = $row["bild"];
    $product["preis"] = $row["preis"];

array_map($product, "utf8_encode"); // encode array values
$products[] = $product; // insert product into array
}
$data = array(
//'success'   => 1,
'products' => $products
);
}
echo json_encode($data); // make it slightly more readable
?>

Solution

  • Slightly cleaned up, should work now:

    $products = array();
    while ($row = mysql_fetch_array($result)) {
        $product = array();
        $product["pid"] = $row["pid"];
        [...]
    
        array_map("utf8_encode", $product); // encode array values
        $products[] = $product; // insert product into array
    }
    
    $data = array(
        'success'   => 1,
        'products' => $products
    );
    
    echo json_encode($data, JSON_PRETTY_PRINT); // make it slightly more readable