PHP - Access first index of array of SimpleXML::xp

2019-09-14 22:34发布

问题:

I am using SimpleXML to get an element of an XML object specified by tag name and attribute... as follows:

$result = $xml->xpath('Stat[@Type="Venue"]');
$venue  = $result[0];

This works fine.

However... the following shortening gives me an error

$venue = $xml->xpath('Stat[@Type="Venue"]')[0];

PHP Parse error:  syntax error, unexpected '[' in /var/www/handler.php on line 10

I've got to be being stupid.... but I cannot seem to figure this out.

回答1:

You can't use an array like that. You need to pass it to a variable like so

$venue = $xml->xpath('Stat[@Type="Venue"]');
echo $venue[0];

I think in PHP 5.4 you will have the ability to access array from objects, but don't quote me on that.

Edit: Sorry about that, I copied and pasted the code from the OP. [0] slipped from my radar!



回答2:

New features PHP 5.4.0

Function array dereferencing has been added, e.g. foo()[0].

Use PHP 5.4.0 or higher.



回答3:

Alright, there's a couple of ways to do this, besides how Eli suggested. The first and easiest for you to implement would be to use current(). I found this in a similar post here, so I can't take credit for this one :)

$vanue = current(($xml->xpath('Stat[@Type="Venue"]')));

The second solution is to use an XPATH query. The only reason to use a query over xpath is if you need to evaluate an expression. Everything I can find says this should also work for you, but as I said, is not necessary and may not even work with your version of PHP. I know it doesn't with mine, so obviously I wasn't able to test it.

$doc = new DOMDocument;
$doc->Load($file);
$xpath = new DOMXPath($doc);
$query = 'Stat[@Type="Venue"]';
$venue = $xpath->query($query)->item(0);