Php 使用简单的XML和xpath解析XML文件

Php 使用简单的XML和xpath解析XML文件,php,xml,xpath,simplexml,Php,Xml,Xpath,Simplexml,我正在尝试从此文件中获取节点“/entry/comment[type=“subcellularLocation”]/subcellularLocation/location”的值 我正在使用SimpleXML和xpath,但无法通过以下方式访问此节点: $var = "http://www.uniprot.org/uniprot/P12345.xml"; $Unip_result= new SimpleXMLElement($var, NULL, TRUE); $value=$Unip_res

我正在尝试从此文件中获取节点“/entry/comment[type=“subcellularLocation”]/subcellularLocation/location”的值

我正在使用SimpleXML和xpath,但无法通过以下方式访问此节点:

$var = "http://www.uniprot.org/uniprot/P12345.xml";
$Unip_result= new SimpleXMLElement($var, NULL, TRUE);

$value=$Unip_result->xpath("/entry/comment[@type='subcellular location']");

结果是一个空数组…

XML有名称空间,您需要为它注册一个前缀,并在XPath表达式中使用前缀。选中
SimpleXMLElement::registerXpathNamespace()

您的XML具有默认名称空间(没有前缀的名称空间:
xmlns=“…”
)。在祖先的默认名称空间中考虑声明默认名称空间的元素及其所有不带前缀和不同默认名称空间的后代。因此,您需要注册一个指向默认命名空间URI的前缀,并在XPath中使用该前缀:

$var = "http://www.uniprot.org/uniprot/P12345.xml";
$Unip_result = new SimpleXMLElement($var, NULL, TRUE);
$Unip_result->registerXPathNamespace('ns', 'http://uniprot.org/uniprot');

$value = $Unip_result->xpath("/ns:uniprot/ns:entry/ns:comment[@type='subcellular location']");