0

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
adam
  • 22,404
  • 20
  • 87
  • 119
  • That syntax `foo()[]` is called _array dereferencing_, and is brand new to PHP 5.4. it won't work in earlier versions. – Michael Berkowski Mar 13 '12 at 15:32
  • Recommended reading: [PHP syntax for dereferencing function result (Apr 2009)](http://stackoverflow.com/q/742764/367456) and [PHP: Access Array Value on the Fly (Apr 2008)](http://stackoverflow.com/q/13109/367456) – hakre Jul 13 '13 at 10:03

3 Answers3

2

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!

Eli
  • 4,329
  • 6
  • 53
  • 78
0

New features PHP 5.4.0

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

Use PHP 5.4.0 or higher.

Oleja
  • 1
  • 1
0

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);
Community
  • 1
  • 1
mseancole
  • 1,662
  • 4
  • 16
  • 26