使用xpath获取$ variable值时进行数组到字符串的转换通知 [英] Array to String conversion notice when getting $variable value with xpath

查看:261
本文介绍了使用xpath获取$ variable值时进行数组到字符串的转换通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用xpath在以下供稿中获取类型元素的名称属性.

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">

为此,我正在使用

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

然后使用

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

我认为

,但不是返回我期望的"F1冠军" ,而是得到一个:

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

数组到字符串的转换

Array to string conversion

注意,但是我不确定为什么,我认为xpath会将@name的值作为字符串返回?

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

推荐答案

simeplexml 中,xpath()方法始终返回array.因此,它不会返回字符串,并且您会看到警告,因为您将数组当作字符串来使用(将其输出).在PHP中将数组转换为字符串时,您会得到通知,字符串为"Array" .

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".

您发现在PHP手册中记录为xpath() s方法返回类型的内容: http://php .net/simplexmlelement.xpath 以及有关字符串的PHP手册(向下滚动/搜索以下内容):

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

数组总是转换为字符串"Array";因此,echoprint本身无法显示数组的内容.要查看单个元素,请使用诸如echo $arr['foo']的构造. [...]

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']. [...]

该规则的唯一例外是,如果您的xpath查询包含错误,则返回值将为FALSE.

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

因此,如果您要查找第一个元素,则可以使用 list语言构造(如果您的xpath查询没有任何语法错误,并且至少返回一个节点):

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');
^^^^^^^^^^^^^^^^^^

如果您使用的是PHP 5.4,还可以直接访问第一个数组值:

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];
                                                                 ^^^

这篇关于使用xpath获取$ variable值时进行数组到字符串的转换通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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