Home >Backend Development >PHP Tutorial >How to Access Object Properties with Invalid or Integer Names in PHP?
JSON decoding in PHP often results in objects with properties that have invalid names. This inconsistency makes it difficult to access these properties using standard object syntax.
Properties with valid variable names can be accessed using dot notation:
$data = '{ "name": "John Doe" }'; $obj = json_decode($data); echo $obj->name; // Output: John Doe
Accessing properties with integer or other invalid names is not as straightforward. PHP has a few quirks that can cause errors:
$data = '{ "42": "The Answer" }'; $obj = json_decode($data); echo $obj->{'42'}; // Output: The Answer
$data = '{ "123": "Three Digits" }'; $obj = json_decode($data); echo $obj->{'123'}; // Error: syntax error
$obj = new stdClass; $obj->{'123'} = 'Three Digits'; echo $obj->{'123'}; // Output: Three Digits
To access properties with invalid names, consider these options:
$obj = json_decode($data); $arr = (array) $obj->highlighting; $value = $arr['448364']['Data']['0'];
function recursive_cast_to_array($obj) { $arr = (array) $obj; foreach ($arr as &$value) { if (is_object($value)) { $value = recursive_cast_to_array($value); } } return $arr; } $arr = recursive_cast_to_array($obj); $value = $arr['highlighting']['448364']['Data']['0'];
$arr = json_decode(json_encode($obj), true); $value = $arr['highlighting']['448364']['Data']['0'];
Note that JSON functions require UTF-8 encoding for all strings.
The above is the detailed content of How to Access Object Properties with Invalid or Integer Names in PHP?. For more information, please follow other related articles on the PHP Chinese website!