【问题标题】:Get a web page XML code using php and use XPATH on it使用 php 获取网页 XML 代码并在其上使用 XPATH
【发布时间】:2017-03-30 05:27:24
【问题描述】:

也许这是一个以前回答过的问题,但我在 Web 开发中很菜鸟。 我正在尝试从此页面获取完整的 XML 文本:

Human Genome

而且,我需要在该代码中执行一些 XPath 查询,例如“获取 ID”等。 例如:

//eSearchResult/IdList/Id/node()

如何获取 php 对象中的完整 XML 以通过 XPath 查询请求数据?

我之前用过这段代码:

<?php
$text = $_REQUEST['text'];
$xmlId = simplexml_load_file('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gene&amp;term='.$text.'%5bGene%20Name%5d+AND+%22Homo%20sapiens%22%5bOrganism');
$id = $xmlId->IdList[0]->Id;
$xmlGeneralData = simplexml_load_file('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gene&amp;id='.$id.'&amp;retmode=xml');
$geneName = $xmlGeneralData->DocumentSummarySet->DocumentSummary[0]->Name;
$geneDesc = $xmlGeneralData->DocumentSummarySet->DocumentSummary[0]->Description;
$geneChromosome = $xmlGeneralData->DocumentSummarySet->DocumentSummary[0]->Chromosome;
echo "Id: ".$id."\n";
echo "Name: ".$geneName."\n";
echo "Description: ".$geneDesc."\n";
echo "Chromosome: ".$geneChromosome."\n";?>

但是,根据教授的说法,这段代码不使用 Xpath 查询,需要页面使用它。

有人可以帮助我或解释我该怎么做吗?

【问题讨论】:

标签: php xml xpath


【解决方案1】:

这是转换为 Xpath 查询的代码。

<?php

$text = $_REQUEST['text'];
$xmlId = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=gene&amp;term='.$text.'%5bGene%20Name%5d+AND+%22Homo%20sapiens%22%5bOrganism';

//Load XML and define Xpath
$xml_id = new DOMDocument();
$xml_id->load($xmlId);
$xpath = new DOMXPath($xml_id);

//Xpath query to get ID
$elements = $xpath->query("//eSearchResult/IdList/Id");

//Loop through result of xpath query and store in array of ID
if ($elements->length >0) {
    foreach ($elements as $entry) {
        $id[] = $entry->nodeValue;
    }
}

echo "Id: ".$id[0]."\n";

//Output the first string of ID array from xpath result set
$xmlGeneralData = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gene&amp;id='.$id[0].'&amp;retmode=xml';

//Load XML and define Xpath
$xml_gd = new DOMDocument();
$xml_gd->load($xmlGeneralData);
$xpath = new DOMXPath($xml_gd);

//Xpath query to search for Document Summary with first string of ID array from previous result set
$elements = $xpath->query("//eSummaryResult/DocumentSummarySet/DocumentSummary[@uid='".$id[0]."']");

//Loop through result of xpath query and find nodes and print out the result
if ($elements->length >0) {
    foreach ($elements as $entry) {
        echo "Name: ".$entry->getElementsByTagName('Name')->item(0)->nodeValue."\n";
        echo "Description: ".$entry->getElementsByTagName('Description')->item(0)->nodeValue."\n";
        echo "Chromosome: ".$entry->getElementsByTagName('Chromosome')->item(0)->nodeValue."\n";
    }
}

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 2022-01-19
    • 2015-12-05
    • 1970-01-01
    • 2011-12-21
    • 2012-04-24
    • 1970-01-01
    相关资源
    最近更新 更多