1

I'm quite new to SimpleXML and using xpath within it. I wasn't sure whether to post this query within the original posting or here, so I linked to here form the original posting.

In working through several test scripts, I came across this posting, and I've been attempting to make one of the accepted answers work. However, when I attempt to use the xpath version of the accepted answer work, I get the error message:

Undefined offset: 0 

I've tested xpath in other ways, to verify that it is installed and functional. Thanks for any leads.

I have duplicated the OP's xml file, along with the accepted answer code:

XML:

<data>
  <poster name="E-Verify" id="everify">
    <full_image url="e-verify-swa-poster.jpg"/>
    <full_other url=""/>
  </poster>
  <poster name="Minimum Wage" id="minwage">
    <full_image url="minwage.jpg"/>
    <full_other url="spa_minwage.jpg"/>
  </poster>
</data>

PHP Code:

<?php
$url = "test_b.xml";
$xml = simplexml_load_file($url);
$main_url = $xml->xpath('name[@id="minwage"]/full_image')[0];
?>
buck1112
  • 504
  • 8
  • 24
  • 1
    Your xpath expression is looking for an element called ``, which doesn't exist. Do you mean `poster`? – iainn Jan 08 '18 at 17:28
  • I copied it from the op here: https://stackoverflow.com/questions/9696545/simplexml-get-node-child-based-on-attribute I had thought the same - in my tests, using 'poster' in xpath worked... – buck1112 Jan 08 '18 at 18:17

1 Answers1

3

Your XPath was looking for a non-existant element called name and not finding it. This will mean there isn't a 0 element to fetch using the [0]. I've changed the element name to poster and in this example I fetch the url attribute, but you can change it to whatever else you need...

$main_url = $xml->xpath('//poster[@id="minwage"]/full_image/@url')[0];
echo $main_url;

gives...

minwage.jpg
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Thanks - it's good to know that I was almost there. Does the [0] specify an array level within the @url variable? – buck1112 Jan 08 '18 at 18:22
  • 1
    When you use `xpath` it will return an array of matching elements. So it's just a case of `[0]` will be the first match. – Nigel Ren Jan 08 '18 at 18:23
  • One more question ... why can't url be put in brackets, instead of after the forward slash, like was done with id and poster? e.g. xpath('//poster[id="minwage"]/full_image[url]')[0] In the xml, it looks like url is an attribute, just like id is. I tried it, but it does not work, but I'm unsure why. Thanks. (note: I had to remove the @ signs, due to confusion with users, here). – buck1112 Jan 08 '18 at 23:34
  • Square brackets in an XPath expression are slightly different, if you used `//full_image[@url]` this would mean to find any full_image which has a url attribute. Whereas `//full_image[url]` mean to find a full_image element which has a url element inside it. So [] is used as a condition in XPath and for arrays in PHP. – Nigel Ren Jan 09 '18 at 07:09