Array to String conversion notice when getting $variable value with xpath

后端 未结 2 585
-上瘾入骨i
-上瘾入骨i 2020-12-21 18:12

Im trying to get the name atriburte of the type element in the following feed using xpath.



        
相关标签:
2条回答
  • 2020-12-21 18:51

    EDIT: use list() to get just one value instead of an array:

    list($market_name) = $wh_xml->xpath('//type/@name');
    echo $market_name;
    

    see it working: http://3v4l.org/rNdMo

    0 讨论(0)
  • 2020-12-21 19:03

    In simeplexml the xpath() method always returns an array. Because of that, it does not return a string and you see the warning because you used the array as if it were a string (outputting it). When you convert an array to a string in PHP, you will get the notice and the string is "Array".

    You find that documented as the xpath()s method return-type in the PHP manual: http://php.net/simplexmlelement.xpath and also in the PHP manual about strings (scroll down/search the following):

    Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. [...]

    The only exception to that rule is if your xpath query contains an error, then the return value will the FALSE.

    So if you're looking for the first element, you can use the list language construct (if your xpath-query does not have any syntax errors and is returning at least one node):

    list($market_name) = $wh_xml->xpath('/response/jonny/class/type/@name');
    ^^^^^^^^^^^^^^^^^^
    

    If you're using PHP 5.4 you can also directly access the first array value:

    $market_name = $wh_xml->xpath('/response/jonny/class/type/@name')[0];
                                                                     ^^^
    
    0 讨论(0)
提交回复
热议问题