我怎样才能访问数组/对象吗? [英] How can I access an array/object?

查看:192
本文介绍了我怎样才能访问数组/对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的数组,当我做的print_r(array_values​​($ GET_USER)); ,我得到:

 阵列(
          [0] => 10499478683521864
          [1] => 1983年7月22日
          [2] => email@saya.com
          [3] =>艾伦[4] =>男
          [5] => Malmsteen的
          [6] => https://www.facebook.com app_scoped_user_id / 1049213468352864 /
          [7] => stdClass的对象(
                   [ID] => 102173722491792
                   [名] =>印度尼西亚雅加达
          )
          [8] => id_ID
          [9] =>厄尔尼诺
          [10] =>艾伦厄尔尼诺Malmsteen的
          [11] => 7
          [12] => 2015-05-28T04:09:50 + 0000
          [13] => 1
        )

我试图访​​问该数组如下:

 回声$ GET_USER [0];

但是,这显示了我:


  

0未定义


注意:

我从这个数组中的 Facebook的SDK 4 ,所以我不知道原来阵列strucutre。

我怎么可以访问作为一个例子值 email@saya.com 从数组?


解决方案

要访问阵列对象你如何使用两个不同的运营商

阵列

要访问数组元素必须为使用 [] 或你看不到那么多,但你也可以使用 {}

 回声$阵列[0];
回声$阵列{0};
//两者是等价的,可互换

声明数组和访问数组元素之间的差异

定义数组和访问数组元素是两回事。所以不要混合起来。

要定义你可以使用一个数组阵列()或PHP> = 5.4 [] 和分配/设置阵列/ -element。而当您访问一个数组元素与 [] {} 如上所述你得到一个数组的值元素反对设置元素。

 // 声明的数组
$ arrayA = 阵列( / *有些东西在这里* / ;
$ arrayB = [ / *有些东西在这里* / ] ; //仅用于PHP> = 5.4 //的访问的数组元素
回声$阵列的 [ 0 ] ;
回声$阵列 { 0 } 的;

访问数组元素

要访问阵列中的一个特定的元素,你可以使用任何前pression在 [] {} 然后计算为关键要访问:

 $阵列[(任何Ex pression)]

所以要知道你的关键使用什么前pression它是如何获得通过PHP PTED间$ P $:

回声$阵列[ 0 ]; //关键是一个整数;它访问0元
回声$阵列[0]; //关键是A 字符串;它访问0元
回声$阵列[字符串]; //关键是A 字符串;它访问的元素与键字符串
回声$阵列[]; //关键是A ,并获取与相应的值代替
回声$阵列[]; //关键也是,而不是一个字符串
回声$阵列[ $ anyVariable ] //关键是A 变量,并得到与在'$ anyVariable'的值替换
回声$阵列[ functionXY()]; //关键是在返回值的功能

访问多维数组

如果你在对方的多个阵列您只需一个多维数组。要在子阵列访问数组元素,您只需要使用多个 []

 回声$阵列[firstSubArray] [SecondSubArray] [ElementFromTheSecondSubArray]
         //├─────────────┘├──────────────┘├──────────────── ────────────┘
         //││└──第三阵列尺寸;
         //│└────────────────────二维数组尺寸;
         // └───────────────────────────────────── 1阵列尺寸;

对象

要访问你必须使用一个对象的属性 - 方式>

回声$对象的  - > 的财产;

如果您有其他对象的对象,你只需要使用多个 - 方式> 来得到你的对象属性

 回声$ objectA-> objectB->财产;


  

注意:


  
  

      
  1. 另外你要小心,如果你有一个属性名称是无效的!所以看到所有的问题,您可以与一个无效的属性名称面临看到这个问题/答案。尤其是这一个,如果你在属性名的开头编号为


  2.   
  3. 您只能从公共知名度访问属性在课堂外。否则(私有或保护),你需要一种方法或反射,你可以用它来获得属性的值。


  4.   

阵列,放大器;对象

现在,如果你有数组和对象相互混合,你只需要看看,如果你现在访问数组元素或对象属性,并使用相应的操作吧。

 //对象
回声$对象 - > anotherObject-> propertyArray [elementOneWithAnObject] - >属性;
    //├────┘├───────────┘├───────────┘├─────────────── ───────┘├──────┘
    //││││└──财产;
    //│││└─────────────────────────────数组元素(对象);使用 - > 要访问的属性的属性
    //││ └───────────────────────────────────────────阵列(属性);使用 [] 要访问数组元素elementOneWithAnObject
    //│ └──────────────────────────────────────────────────────────属性(对象);使用 - > 要访问属性propertyArray
    //└──────────────────────────────────────────────────────────────────对象;使用 - > 要访问属性anotherObject
//数组
回声$阵列[arrayElement] [anotherElement] - >对象 - >属性[元素];
    //├───┘├────────────┘├──────────────┘├────┘├────── ┘├───────┘
    //│││││└──数组元素;
    //││││└───────────属性(数组);使用 [] 要访问数组元素元素
    //│││└───────────────────属性(对象);使用 - > 要访问的属性的属性
    //││ └──────────────────────────────────────数组元素(对象);使用 - > 要访问的属性的对象
    //│ └──────────────────────────────────────────────────────数组元素(数组);使用 [] 要访问数组元素anotherElement
    //└────────────────────────────────────────────────────────────阵列;使用 [] 要访问数组元素arrayElement

我希望这给你一个粗略的想法如何访问数组和对象,它们嵌套在对方的时候。


  

注意:


  
  

      
  1. 如果它被称为一个数组或对象取决于您的变量的最外层部分。因此, [新一个StdClass] 阵列即使有(嵌套)在它的内部对象和 $对象 - &GT;物业=阵列(); 是<强>对象即使有(嵌套)阵列内


      
      

    而如果你不知道你是否有一个对象或数组,只是使用的 的GetType()


  2.   

  
  


  
  <醇开始=2>
  

  • 不要让自己的糊涂,如果有人使用其他的编码风格比你:

      //这两种方法/风格工作,并访问相同的数据
    回声$对象 - &GT; anotherObject-&GT; propertyArray [elementOneWithAnObject] - &GT;财产;
    回声$对象 - &GT;
            anotherObject
             - &GT; propertyArray
            [elementOneWithAnObject] - &GT;
            属性;//这两种方法/风格工作,并访问相同的数据
    回声$阵列[arrayElement] [anotherElement] - &GT;对象 - &GT;财产[元素];
    回声$阵列[arrayElement]
         [anotherElement] - &GT;
             目的
        - &GT;财产[元素];


  •   

    数组,对象和循环

    如果你不就是想在你的嵌套数组/对象来访问一个元素可以循环并通过特定维度的值。

    有关这一点,你只需要访问超过您要循环的维度,然后你可以遍历该维度的所有值。

    作为一个例子,我们取一个数组,但它也可以是一个对象:

     阵列(
        [数据] =&GT;阵列(
                [0] =&GT; stdClass的对象(
                        [propertyXY] =&GT; 1
                    )
                [1] =&GT; stdClass的对象(
                        [propertyXY] =&GT; 2
                    )
                [2] =&GT; stdClass的对象(
                        [propertyXY] =&GT; 3
                   )
            )

    如果您遍历第一维,你会得到的第一个维度的所有值:

    的foreach( $阵列为$键=> $值)

    表示在这里的第一个维度,你将只需要1元的键( $键数据和值( $值

     阵列(//重点:数组
        [0] =&GT; stdClass的对象(
                [propertyXY] =&GT; 1
            )
        [1] =&GT; stdClass的对象(
                [propertyXY] =&GT; 2
            )
        [2] =&GT; stdClass的对象(
                [propertyXY] =&GT; 3
            )

    如果您遍历所有的第二个方面,你会从第二个维度的所有值:

    的foreach( $阵列[数据] 为$键=> $值)

    表示在这里的第二个方面,你将不得不用钥匙3元( $键 0 1 2 和值( $值

      stdClass的对象(主要//:0
        [propertyXY] =&GT; 1

    stdClass的对象(//重点:1
        [propertyXY] =&GT; 2

    stdClass的对象(主要//:2
        [propertyXY] =&GT; 3

    这样,你可以通过任何尺寸环要不管它是一个数组或对象。

    的var_dump() / 的print_r() / var_export() 输出

    所有这些3调试功能输出的相同的数据,只是以另一种格式或具有一些元数据(例如类型,大小)。所以在这里我要告诉你如何要读这些函数的输出知道/去如何从您的阵列/对象访问某些数据的方式。

    输入数组:

      $阵列= [
        钥匙=&GT; (对象)
            财产=&GT; [1,2,3]
        ]
    ];

    的var_dump()输出:

     阵列(1){
      [钥匙] =&GT;
      对象(stdClass的)#1(1){
        [属性] =&GT;
        阵列(3){
          [0] =&GT;
          INT(1)
          [1] =&GT;
          INT(2)
          [2] =&GT;
          INT(3)
        }
      }
    }

    的print_r()输出:

     阵列

        [关键] =&GT; stdClass的对象
            (
                [属性] =&GT;排列
                    (
                        [0] =&GT; 1
                        [1] =&GT; 2
                        [2] =&GT; 3
                    )        ))

    var_export()输出:

     阵列(
      钥匙= GT;
      stdClass的:: __ set_state(阵列(
         财产=&GT;
        阵列(
          0 =&GT; 1,
          1 =&GT; 2,
          2 =&GT; 3,
        )
      ))

    所以,你可以看到所有的输出都差不多pretty。如果你现在要访问的值2你可以从你要访问和工作的方式到了左上方本身的价值,开始。

    1。我们首先看到,该值2与数组中的键1

     阵列(3){ //的var_dump()
      [0] =>
      INT(1)
      的 [1] =>
      INT(2)

      [2] =>
      INT(3)
    }

     阵列 //的print_r()

      [0] => 1
      的 [1] => 2
      [2] => 3

     阵列( // var_export()
      0 => 1,
       1 => 2日
      2 => 3,
    ),

    这意味着我们必须使用 [] / {} 与访问值2 [1] ,因为该值的键/索引1。

    2。接下来,我们看到,该阵列分配给一个属性与对象的名称属性

     对象(stdClass的)#1(1) { //的var_dump()
       [属性] =>
        / *阵列这里* /
    }

     stdClass的对象 //的print_r()

       [属性] => / *阵列这里* /

      stdClass的 :: __ set_state 阵列(// var_export()
      属性 =>
        / *阵列这里* /
    )的),

    这意味着我们必须使用 - &GT; 来访问对象的属性,例如 - &GT;物业

    所以到现在为止,我们知道,我们必须使用 - 方式&gt;属性[1]

    3。而在我们看到最后,最外面的是一个数组

     阵列(1){ //的var_dump()
       [钥匙] =>
        / *对象和数组这里* /
    }

     阵列 //的print_r()

       [关键] =>
        / *对象和数组这里* /

     阵列( // var_export()
      关键 =>
        / *对象和数组这里* /

    我们知道,我们有 [] ,我们在这里看到,我们不得不使用 [访问数组元素关键] 即可访问该对象。现在,我们可以把所有这些部分组合在一起,并写:

     回声$阵列[钥匙]  - &GT;物业[1];

    和输出将是:

      2

    不要让PHP巨魔你!

    有几件事情,你要知道,让你不花时间在上面找到他们。


    1. 隐字

      有时候,你必须在你的钥匙,你不要在浏览器中第一次看看到的字符。然后你会问自己,为什么你不能访问的元素。这些字符可以是:标签( \\ t ),新线( \\ n ),空格或html标签(如: &LT; / p&GT; &LT; b&GT; )等

      作为一个例子,如果你看一下的print_r()的输出,你会看到:

       阵列([关键] =&gt;此处)

      然后你正在尝试与访问元素:

       回声$改编[钥匙];

      不过,你所得到的通知:


        

      注意:未定义指数:键


      这是一个很好的迹象,必须有一些隐藏的人物,因为你不能访问该元素,即使密钥似乎pretty正确的。

      这里的技巧是使用的var_dump() +看看你的源代码code! (备选: highlight_string(的print_r($变量,TRUE));

      和所有你也许看到这样的东西突然的:

       阵列(1){
        [&LT; / B&GT;
      钥匙] =&GT;
        串(4)这里
      }

      现在你会看到,你的钥匙有一个HTML标记在IT +新行字符,这并没有在第一时间看到了,因为的print_r()和浏览器没有表明

      所以,现在,如果你尝试这样做:

       回声$改编[&LT; / B&GT; \\ nkey];

      您会得到你想要的输出:

        HERE


    2. 永远不要相信的输出的print_r()的var_dump()如果你看一下XML

      您可能会加载到的对象的XML文件或字符串,例如

       &LT;?XML版本=1.0编码=UTF-8&GT?;
      &LT; RSS和GT;
          &LT;项目&GT;
              &LT; title属性=XYAB =XY&GT;测试与LT; /标题&GT;
          &LT; /项目&GT;
      &LT; / RSS&GT;

      现在,如果你使用的var_dump()的print_r()您将看到:

        SimpleXMLElement对象

          [项目] =&GT; SimpleXMLElement对象
          (
              [标题] =&GT;测试
          ))

      所以,你可以看到你没有看到标题的属性。因此,正如我说永远不要相信的var_dump的输出()的print_r()当你有一个XML对象。始终使用 asXML() 查看完整的XML文件/串。

      因此​​,只要使用下面所示的方法之一:

       回声$ XML的&GT; asXML(); //并期待到源$ C ​​$ Chighlight_string($ XML-&GT; asXML());标题(内容类型:text / XML);
      回声$ XML的&GT; asXML();

      ,然后你会得到的输出:

       &LT;?XML版本=1.0编码=UTF-8&GT?;
      &LT; RSS和GT;
          &LT;项目&GT;
              &LT; title属性=XYAB =XY&GT;测试与LT; /标题&GT;
          &LT; /项目&GT;
      &LT; / RSS&GT;



    有关更多信息,请参见:

    常规(符号,错误)

    属性名称的问题

    I have the following array and when I do print_r(array_values($get_user));, I get:

    Array (
              [0] => 10499478683521864
              [1] => 07/22/1983
              [2] => email@saya.com
              [3] => Alan [4] => male
              [5] => Malmsteen
              [6] => https://www.facebook.com  app_scoped_user_id/1049213468352864/
              [7] => stdClass Object (
                       [id] => 102173722491792
                       [name] => Jakarta, Indonesia
              )
              [8] => id_ID
              [9] => El-nino
              [10] => Alan El-nino Malmsteen
              [11] => 7
              [12] => 2015-05-28T04:09:50+0000
              [13] => 1
            ) 
    

    I tried to access the array as followed:

    echo $get_user[0];
    

    But this displays me:

    undefined 0

    Note:

    I get this array from the Facebook SDK 4, so I don't know the original array strucutre.

    How can I access as an example the value email@saya.com from the array?

    解决方案

    To access an array or object you how to use two different operators.

    Arrays

    To access array elements you have to use either [] or which you don't see that much, but which you can also use is {}.

    echo $array[0];
    echo $array{0};
    //Both are equivalent and interchangeable
    

    Difference between declaring an array and accessing an array element

    Defining an array and accessing an array element are two different things. So don't mix them up.

    To define an array you can use array() or for PHP >=5.4 [] and you assign/set an array/-element. While when you are accessing an array element with [] or {} as mentioned above you get the value of an array element opposed to setting an element.

    //Declaring an array
    $arrayA = array ( /*Some stuff in here*/ );
    $arrayB = [ /*Some stuff in here*/ ]; //Only for PHP >=5.4
    
    //Accessing an array element
    echo $array[0];
    echo $array{0};
    

    Access array element

    To access a particular element in an array you can use any expression inside [] or {} which then evaluates to the key you want to access:

    $array[(Any expression)]
    

    So just be aware of what expression you use as key and how it gets interpreted by PHP:

    echo $array[0];            //The key is an integer; It accesses the 0's element
    echo $array["0"];          //The key is a string; It accesses the 0's element
    echo $array["string"];     //The key is a string; It accesses the element with the key 'string'
    echo $array[CONSTANT];     //The key is a constant and it gets replaced with the corresponding value
    echo $array[cOnStAnT];     //The key is also a constant and not a string
    echo $array[$anyVariable]  //The key is a variable and it gets replaced with the value which is in '$anyVariable'
    echo $array[functionXY()]; //The key will be the return value of the function
    

    Access multidimensional array

    If you have multiple arrays in each other you simply have a multidimensional array. To access an array element in a sub array you just have to use multiple [].

    echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"]
             // ├─────────────┘  ├──────────────┘  ├────────────────────────────┘
             // │                │                 └── 3rd Array dimension;
             // │                └──────────────────── 2d  Array dimension;
             // └───────────────────────────────────── 1st Array dimension;
    

    Objects

    To access an object property you have to use ->.

    echo $object->property;
    

    If you have an object in another object you just have to use multiple -> to get to your object property.

    echo $objectA->objectB->property;
    

    Note:

    1. Also you have to be careful if you have a property name which is invalid! So to see all problems, which you can face with an invalid property name see this question/answer. And especially this one if you have numbers at the start of the property name.

    2. You can only access properties with public visibility from outside of the class. Otherwise (private or protected) you need a method or reflection, which you can use to get the value of the property.

    Arrays & Objects

    Now if you have arrays and objects mixed in each other you just have to look if you now access an array element or an object property and use the corresponding operator for it.

    //Object
    echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
        //├────┘  ├───────────┘  ├───────────┘ ├──────────────────────┘   ├──────┘
        //│       │              │             │                          └── property ; 
        //│       │              │             └───────────────────────────── array element (object) ; Use -> To access the property 'property'
        //│       │              └─────────────────────────────────────────── array (property) ; Use [] To access the array element 'elementOneWithAnObject'
        //│       └────────────────────────────────────────────────────────── property (object) ; Use -> To access the property 'propertyArray'
        //└────────────────────────────────────────────────────────────────── object ; Use -> To access the property 'anotherObject'
    
    
    //Array
    echo $array["arrayElement"]["anotherElement"]->object->property["element"];
        //├───┘ ├────────────┘  ├──────────────┘   ├────┘  ├──────┘ ├───────┘
        //│     │               │                  │       │        └── array element ; 
        //│     │               │                  │       └─────────── property (array) ; Use [] To access the array element 'element'
        //│     │               │                  └─────────────────── property (object) ; Use -> To access the property 'property'
        //│     │               └────────────────────────────────────── array element (object) ; Use -> To access the property 'object'
        //│     └────────────────────────────────────────────────────── array element (array) ; Use [] To access the array element 'anotherElement'
        //└──────────────────────────────────────────────────────────── array ; Use [] To access the array element 'arrayElement'
    
    

    I hope this gives you a rough idea how you can access arrays and objects, when they are nested in each other.

    Note:

    1. If it is called an array or object depends on the outermost part of your variable. So [new StdClass] is an array even if it has (nested) objects inside of it and $object->property = array(); is an object even if it has (nested) arrays inside.

      And if you are not sure if you have an object or array, just use gettype().

    1. Don't get yourself confused if someone uses another coding style than you:

      //Both methods/styles work and access the same data
      echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
      echo $object->
              anotherObject
              ->propertyArray
              ["elementOneWithAnObject"]->
              property;
      
      //Both methods/styles work and access the same data
      echo $array["arrayElement"]["anotherElement"]->object->property["element"];
      echo $array["arrayElement"]
           ["anotherElement"]->
               object
         ->property["element"];
      

    Arrays, Objects and Loops

    If you don't just want to access a single element you can loop over your nested array / object and go through the values of a particular dimension.

    For this you just have to access the dimension over which you want to loop and then you can loop over all values of that dimension.

    As an example we take an array, but it could also be an object:

    Array (
        [data] => Array (
                [0] => stdClass Object (
                        [propertyXY] => 1
                    )    
                [1] => stdClass Object (
                        [propertyXY] => 2
                    )   
                [2] => stdClass Object (
                        [propertyXY] => 3                   
                   )    
            )
    )
    

    If you loop over the first dimension you will get all values from the first dimension:

    foreach($array as $key => $value)
    

    Means here in the first dimension you would only have 1 element with the key($key) data and the value($value):

    Array (  //Key: array
        [0] => stdClass Object (
                [propertyXY] => 1
            )
        [1] => stdClass Object (
                [propertyXY] => 2
            )
        [2] => stdClass Object (
                [propertyXY] => 3
            )
    )
    

    If you loop over the second dimension you will get all values from the second dimension:

    foreach($array["data"] as $key => $value)
    

    Means here in the second dimension you would have 3 element with the keys($key) 0, 1, 2 and the values($value):

    stdClass Object (  //Key: 0
        [propertyXY] => 1
    )
    stdClass Object (  //Key: 1
        [propertyXY] => 2
    )
    stdClass Object (  //Key: 2
        [propertyXY] => 3
    )
    

    And with this you can loop through any dimension which you want no matter if it is an array or object.

    Analyse var_dump() / print_r() / var_export() output

    All of these 3 debug functions output the same data, just in another format or with some meta data (e.g. type, size). So here I want to show how you have to read the output of these functions to know/get to the way how to access certain data from your array/object.

    Input array:

    $array = [
        "key" => (object) [
            "property" => [1,2,3]
        ]
    ];
    

    var_dump() output:

    array(1) {
      ["key"]=>
      object(stdClass)#1 (1) {
        ["property"]=>
        array(3) {
          [0]=>
          int(1)
          [1]=>
          int(2)
          [2]=>
          int(3)
        }
      }
    }
    

    print_r() output:

    Array
    (
        [key] => stdClass Object
            (
                [property] => Array
                    (
                        [0] => 1
                        [1] => 2
                        [2] => 3
                    )
    
            )
    
    )
    

    var_export() output:

    array (
      'key' => 
      stdClass::__set_state(array(
         'property' => 
        array (
          0 => 1,
          1 => 2,
          2 => 3,
        ),
      )),
    )
    

    So as you can see all outputs are pretty similar. And if you now want to access the value 2 you can just start from the value itself, which you want to access and work your way out to the "top left".

    1. We first see, that the value 2 is in an array with the key 1

    array(3) {  //var_dump()
      [0]=>
      int(1)
      [1]=>
      int(2)
      [2]=>
      int(3)
    }
    

    Array  //print_r()
    (
      [0] => 1
      [1] => 2
      [2] => 3
    )
    

    array (  //var_export()
      0 => 1,
      1 => 2,
      2 => 3,
    ),
    

    This means we have to use []/{} to access the value 2 with [1], since the value has the key/index 1.

    2. Next we see, that the array is assigned to a property with the name property of an object

    object(stdClass)#1 (1) {  //var_dump()
      ["property"]=>
        /* Array here */
    }
    

    stdClass Object  //print_r()
    (
      [property] => /* Array here */
    )
    

    stdClass::__set_state(array(  //var_export()
      'property' => 
        /* Array here */
    )),
    

    This means we have to use -> to access the property of the object, e.g. ->property.

    So until now we know, that we have to use ->property[1].

    3. And at the end we see, that the outermost is an array

    array(1) {  //var_dump()
      ["key"]=>
        /* Object & Array here */
    }
    

    Array  //print_r()
    (
      [key] => 
        /* Object & Array here */
    )
    

    array (  //var_export()
      'key' =>
        /* Object & Array here */
    )
    

    As we know that we have to access an array element with [], we see here that we have to use ["key"] to access the object. We now can put all these parts together and write:

    echo $array["key"]->property[1];
    

    And the output will be:

    2
    

    Don't let PHP troll you!

    There are a few things, which you have to know, so that you don't spend hours on it finding them.

    1. "Hidden" characters

      Sometimes you have characters in your keys, which you don't see on the first look in the browser. And then you're asking yourself, why you can't access the element. These characters can be: tabs (\t), new lines (\n), spaces or html tags (e.g. </p>, <b>), etc.

      As an example if you look at the output of print_r() and you see:

      Array ( [key] => HERE ) 
      

      Then you are trying to access the element with:

      echo $arr["key"];
      

      But you are getting the notice:

      Notice: Undefined index: key

      This is a good indication that there must be some hidden characters, since you can't access the element, even if the keys seems pretty correct.

      The trick here is to use var_dump() + look into your source code! (Alternative: highlight_string(print_r($variable, TRUE));)

      And all of the sudden you will maybe see stuff like this:

      array(1) {
        ["</b>
      key"]=>
        string(4) "HERE"
      }
      

      Now you will see, that your key has a html tag in it + a new line character, which you didn't saw in the first place, since print_r() and the browser didn't showed that.

      So now if you try to do:

      echo $arr["</b>\nkey"];
      

      You will get your desired output:

      HERE
      

    2. Never trust the output of print_r() or var_dump() if you look at XML

      You might have an XML file or string loaded into an object, e.g.

      <?xml version="1.0" encoding="UTF-8" ?> 
      <rss> 
          <item> 
              <title attribute="xy" ab="xy">test</title> 
          </item> 
      </rss>
      

      Now if you use var_dump() or print_r() you will see:

      SimpleXMLElement Object
      (
          [item] => SimpleXMLElement Object
          (
              [title] => test
          )
      
      )
      

      So as you can see you don't see the attributes of title. So as I said never trust the output of var_dump() or print_r() when you have an XML object. Always use asXML() to see the full XML file/string.

      So just use one of the methods shown below:

      echo $xml->asXML();  //And look into the source code
      
      highlight_string($xml->asXML());
      
      header ("Content-Type:text/xml");
      echo $xml->asXML();
      

      And then you will get the output:

      <?xml version="1.0" encoding="UTF-8"?>
      <rss> 
          <item> 
              <title attribute="xy" ab="xy">test</title> 
          </item> 
      </rss>
      


    For more information see:

    General (symbols, errors)

    Property name problems

    这篇关于我怎样才能访问数组/对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆