Skip to content
Advertisement

PHP json_decode due to json element

My code

<?php
    $result = '{ "nid": 4872, "price": "£35.36", "salePrice": "£35.36", "discount": 0, "message": "x3cdiv class="ajax-cart-status"x3eThe current price has been updated.x3c/divx3e" }';
    
    $arr1 = json_decode($result, true);
    $arr2 = ['text' => 'text2'];
    $arr1 = array_merge($arr1,$arr2);
    
    echo json_encode($arr1);
?>

output

NULL

The issue is in the message key value, I tried to use php stripslashes but doesn’t work

$arr1 = json_decode(stripslashes($result), true);

Any help?

Advertisement

Answer

Looks like someone tried to “intelligently” hexencode payload to survive processing steps with unclean coding… It usually is wise to fix the actual issue, so the code creating such payload instead of trying to cure a symptom. There are however situations where you are unable to do so. Which is when you need to start getting dirty hands:

<?php

function hexcode_decode($string) {
    return preg_replace_callback('#\\x([[:xdigit:]]{2})#ism', function($matches) {
        return chr(hexdec($matches[1]));
    },
    $string);
}

$json = '{ "nid": 4872, "price": "??35.36", "salePrice": "??35.36", "discount": 0, "message": "x3cdiv class="ajax-cart-status"x3eThe current price has been updated.x3c/divx3e" }';
print_r(json_decode(hexcode_decode($json)));

The output is:

stdClass Object
(
    [nid] => 4872
    [price] => ??35.36
    [salePrice] => ??35.36
    [discount] => 0
    [message] => <div class="ajax-cart-status">The current price has been updated.</div>
)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement