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条)

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧