问题描述
我真的很难使它正常工作。 xpath在同一文件的其他功能中也能正常工作。我正在尝试从XML文件中获取特定项目,当我dd()时它可以正常工作。但是,当我尝试将完全相同的代码加载到变量中时,会提示“未定义的偏移量0”。我在Laravel本地工作。
XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<idPkg:Graphic xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="15.1">
<Color Self="Color/u2a64f" Model="Process" Space="RGB" ColorValue="204 204 204" />
</idPkg:Graphic>
function getColor($colorID){ //$colorID = Color/u2a64f
$xml= simplexml_load_file('/Resources/Graphic.xml');
$colorNode = $xml->xpath('//Color[@Self="'.$colorID.'"]');
dd($colorNode[0]->attributes()->ColorValue);
/* outputs:
SimpleXMLElement {#316 ▼
+"0": "204 204 204"
}
*/
$fillColor = $colorNode[0]->attributes()->ColorValue; // Line of error
/* outputs:
ErrorException (E_NOTICE)
Undefined offset: 0
*/
return $fillColor;
}
编辑: 我刚发现的结果:当我用变量的内容替换xpath中的变量时,它起作用了。
function getColor($colorID){ //$colorID = Color/u2a64f
$xml= simplexml_load_file('/Resources/Graphic.xml');
// doesnt work
$path = '//Color[@Self="'.$colorID.'"]';
// does work
$path = '//Color[@Self="Color/u2a64f"]';
$colorNode = $xml->xpath($path);
dd($colorNode[0]->attributes()->ColorValue);
/* outputs:
SimpleXMLElement {#316 ▼
+"0": "204 204 204"
}
*/
$fillColor = $colorNode[0]->attributes()->ColorValue; // Line of error
/* outputs:
ErrorException (E_NOTICE)
Undefined offset: 0
*/
return $fillColor;
}
解决方法
没关系,我自己找到了解决方案。
再次检查我的代码后,我发现有时某些XML节点没有属性FillColor。因此,我首先检查了我的参数是否已设置,然后继续执行xpath。