xpath query on SimpleXML Document - Undefined offset: 0

℡╲_俬逩灬. 提交于 2019-12-11 11:06:34

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/48154956/xpath-query-on-simplexml-document-undefined-offset-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!