0

I have a JSON file like this:

test.json

{
    "barcode": {
        "message": "<?xml version=\"1.0\" encoding = \"utf-8?\"><PrintLetterBarcodeData name=\"ABCD \" gender=\"FEMALE\" yob=\"1964\"/>",
        "format": "PKBarcodeFormatQR",
        "messageEncoding": "iso-8859-1"
    }
}

and a PHP file like this:

test.php

<?php

$JSON = file_get_contents('test.json');
$json_object = json_decode($JSON);
print_r($json_object);

?>

I am trying to read the value for the key "message" under "barcode". I am getting an empty string. Here's what I get when I print the object.

stdClass Object ( [barcode] => stdClass Object ( [message] => [format] => PKBarcodeFormatQR [messageEncoding] => iso-8859-1 ) )

JSON is good, message has XML content. I need to get read that XML content in PHP. Please let me know how I can do that?

Bijoy Thangaraj
  • 5,434
  • 4
  • 43
  • 70

2 Answers2

2

Referencing the message in the object works fine with:

echo $json->barcode->message;

Reading your question though, I don't think you've made it clear what your issue is. If you are having trouble reading your XML object in PHP then it's because your XML is invalid. There is a typo in the declaration - see the before and after below:

<?xml version=\"1.0\" encoding = \"utf-8?\">
<?xml version=\"1.0\" encoding = \"utf-8?\"?>
                                           ^
                                           Missing character

For completeness... then you can simple use simplexml_load_string to parse the message object into a PHP variable and reference the attributes as follows:

$json = json_decode($json);
$xml = simplexml_load_string($json->barcode->message);
echo $xml['name'].' '. $xml['gender'].' '. $xml['yob'];

working example

animuson
  • 53,861
  • 28
  • 137
  • 147
Emissary
  • 9,954
  • 8
  • 54
  • 65
1

This is where you use the second optional parameter in json_decode: http://php.net/manual/en/function.json-decode.php

<?php

$JSON = file_get_contents('test.json');
$json_object = json_decode($JSON, true);
print_r($json_object);
echo $json_object['barcode']['message'];

?>
000
  • 26,951
  • 10
  • 71
  • 101