如何删除SimpleXMLElement对象中的[@attributes]

问题描述 投票:1回答:4
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [domain] => http://www.eatingwell.com/category/publication/magazine /september/october_2009
        )

    [0] => September/October 2009
    [1] => American
    [2] => Easy
    [3] => Diabetes appropriate
    [4] => Healthy weight
    [5] => High calcium
    [6] => Low calorie
    [7] => Low cholesterol
    [8] => Bone Health
    [9] => Super Bowl
    [10] => Recipes & Menus - Fresh
    [11] => Recipes & Menus - Vegetarian
    [12] => Cheese
    [13] => Dairy
    [14] => Greens
    [15] => Vegetables
    [16] => Wheat
    [17] => Whole Grains
    [18] => Vegetarian, other
    [19] => Appetizers 
    [20] => Dinner

    [21] => Bake
    [22] => Fall
    [23] => Spring
    [24] => Summer
    [25] => Winter
    [26] => Budget
    [27] => Entertaining, casual 
    [28] => Everyday favorites
    [29] => Quick (total 30 min. or less)
    [30] => Vegetarian
    [31] => Appetizer
    [32] => Main dish, vegetarian
    [33] => Pizza
)

我想从rss feed中检索类别,但是$bullet =$item->category;pr($bullet);它会显示上面的结果。我只想要数组值[0]到[33]。如何从上面的结果中删除@attributes?

php xml rss simplexml feed
4个回答
0
投票

我假设pr()是一个函数,无论出于何种原因只包装print_r(),在这种情况下,我会告诉你我用SimpleXML问题告诉每个人:不要信任print_r(或var_dump,或任何正常的调试输出函数)。

简单的事实是那些属性不存在。 SimpleXML使用迭代器,魔术方法和其他技巧来提供一个非常方便的“Do Do I Mean”界面,但很难在调试输出中总结它。

如果你想循环所有具有相同名称的元素,写下foreach ( $item->category as $bullet ),你永远不会发现$bullet被设置为任何属性。但是,它将被设置为每个节点的对象,因此,如果您正在执行比echo $bullet更复杂的操作,则可能需要使用(string)$bullet提取文本内容。

如果你想获得一个属性,你不会通过以任何形式查看@attributes,而是通过使用数组样式访问来找到它,例如(string)$bullet['domain']

将你的代码基于the examples in the manual,而不是调试输出,你会得到更远的:)


0
投票

尝试:

unset(xml->attributes()->domain);

-1
投票

根据IMSoP的观察,@属性不是该对象的真实属性。但是,您可以通过执行以下操作来“欺骗”,只要您不再需要与对象作为SimpleXMLElement对象进行交互:

<?php

function purgeAttributes( $object ) {
    foreach ( $object as $key => $value ) {
        if ( gettype( $value ) == 'object' ) {
            $object->$key = purgeAttributes( $value );
        }

        if ( $key == '@attributes' ) {
            unset( $object->$key );
        }
    }

    return $object;
}

$x = SimpleXML_load_string('<foo bar="baz" />');

$x = json_decode( json_encode( $x ) );

$x = purgeAttributes( $x );

var_dump( $x );

-1
投票

我这样做,似乎工作。编码 - >解码应该足以将SimpleXMLElement对象转换为StdClass对象并以您希望的方式运行:

public function cleanXML($ xmlString){

    $xmlString = str_replace(array("\n", "\r", "\t"), '', $xmlString);
    $xmlString = trim(str_replace('"', "'", $xmlString));
    $object = SimpleXML_load_string($xmlString);
    $object = json_decode( json_encode( $object ) );
    foreach ( $object as $key => $value ) {
        if ( $key == '@attributes' ) {
            unset( $object->$key );
        }
    }
    return $object;
}
© www.soinside.com 2019 - 2024. All rights reserved.