dongzhan1570 2013-04-25 15:38
浏览 42
已采纳

使用xpath获取$ variable值时的Array to String转换通知

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

<response request="getHierarchyByMarketType" code="001" 
          message="success" debug="">    
<jonny>    
  <class id="5" name="Formula 1" maxRepDate="2012-12-19" maxRepTime="15:03:34">    
    <type id="4558" name="F1 Championship" lastUpdateDate="2012-11-26"
          lastUpdateTime="16:17:33">

to do this I'm using

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

and then using

<h2>
  <?= $market_name ?>
</h2>

in my view, but instead of it returning my expected "F1 Championship" im getting a:

Array to string conversion

notice, but I'm not sure why, I thought xpath would return the value of @name as a string?

  • 写回答

2条回答 默认 最新

  • dongqiao0953 2013-04-26 11:17
    关注

    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];
                                                                     ^^^
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号