间接修改SimpleXMLElement的重载元素没有影响


Indirect modification of overloaded element of SimpleXMLElement has no effect

我有一个页面到我的网站,我必须解析xml和插入结果到一个数组。但是当我尝试插入数组房间时,我有这个错误:

Indirect modification of overloaded element of SimpleXMLElement has no effect

错误在这一行:

$hotel_array[$id]['rooms'][$i] = $room_array;

这是我的代码:

$hotel_array = array(); 
//$xml->data is a valid xml parsed with simpleXML
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
    $id = (string)$entry2->attributes()->HOTEL_CODE;
    if($entry2->attributes()->HOTEL_CODE=='YYG'){
         $exist = 0;
         if (array_key_exists('YYG', $hotel_array))
        $exist = 1;
         $hotel_array[$id] = $entry2->attributes()->HOTEL_CODE;
             $i=0;
         foreach($entry2->ROOM_DATA as $room){
        $room_array = array();
        $room_array['id'] = $room->attributes()->CCHARGES_CODE;
        $room_array['code'] = $room->attributes()->ROOM_CODE;
        $room_array['name'] = utf8_decode($room->ROOM_NAME);
>attributes()->NO_OF_EXTRA_BEDS;
        $hotel_array[$id]['rooms'][$i] = $room_array;
        $i++;
            }
}
}

您看到的第一个问题是这一行没有完全按照您的要求执行:

$hotel_array[$id] = $entry2->attributes()->HOTEL_CODE;

当您访问SimpleXML对象的子元素或属性时,您返回的是另一个SimpleXML对象。因此,在该语句的末尾,$hotel_array[$id]指向一个SimpleXML对象。然后,当您尝试将其他细节分配给$hotel_array[$id]时,PHP认为您试图以不受支持的方式修改XML本身,从而导致您看到的错误。

我认为你真正想要的是获得该属性的内容,作为一个普通的PHP字符串。这样做的方法是用(string)$variable: 转换为字符串。
$hotel_array[$id] = (string)$entry2->attributes()->HOTEL_CODE;

然而,你有第二个问题:$hotel_array[$id]现在是一个字符串,但几行后,你试图把它作为一个数组:

$hotel_array[$id]['rooms'][$i] = $room_array;

查看代码,$id已经设置为(string)$entry2->attributes()->HOTEL_CODE,并且作为$hotel_array条目的键存储,所以我不确定为什么您需要再次分配它,但如果您这样做,它不能与包含['rooms']键的数组在同一位置。相反,您希望使用以下行之一:

# Just create an empty hash with the key as the hotel code
$hotel_array[$id] = array();
# Add the hotel code into the array, next to the 'rooms' key
$hotel_array[$id]['code'] = (string)$entry2->attributes()->HOTEL_CODE;
# Above combined into one array initialisation, including empty 'rooms' array
$hotel_array[$id] = array(
    'code' => (string)$entry2->attributes()->HOTEL_CODE,
    'rooms' => array()
);

看起来我就像你试图设置一个属性(['rooms'])在SimpleXML元素已经代表了一个属性本身($hotel_array[$id])。

也许我不知道你在做什么,但不应该$hotel_array($id)是一个纯数组在第一个地方($hotel_array[$id] = array();,就是这样)?然后,您可以在其中构建嵌套数组,而不会出现任何问题。