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