首页 > 解决方案 > 如何从 xml url 获取子节点?

问题描述

我得到了这个链接https://www.ncbi.nlm.nih.gov/gene/7128?report=xml&format=text。我正在尝试编写一个代码,从链接中获取 Gene-commentary_heading 中的交互和 GeneOntology。我只有在有 2 个或 3 个节点时才能成功使用此代码,但在这种情况下至少有 6 个或更多节点。有人可以帮助我吗?

Bellow 是我正在寻找的信息的示例(可视化太多了,所以我只展示了一部分)

<Gene-commentary_heading>GeneOntology</Gene-commentary_heading>
  <Gene-commentary_source>
    <Other-source>
      <Other-source_pre-text>Provided by</Other-source_pre-text>
      <Other-source_anchor>GOA</Other-source_anchor>
      <Other-source_url>http://www.ebi.ac.uk/GOA/</Other-source_url>
    </Other-source>
  </Gene-commentary_source>
  <Gene-commentary_comment>
    <Gene-commentary>
      <Gene-commentary_type value="comment">254</Gene-commentary_type>
      <Gene-commentary_label>Function</Gene-commentary_label>
      <Gene-commentary_comment>
        <Gene-commentary>
          <Gene-commentary_type value="comment">254</Gene-commentary_type>
          <Gene-commentary_source>
            <Other-source>
              <Other-source_src>
                <Dbtag>
                  <Dbtag_db>GO</Dbtag_db>
                  <Dbtag_tag>
                    <Object-id>
                      <Object-id_id>3677</Object-id_id>
                    </Object-id>
                  </Dbtag_tag>
                  ...



`$url = "https://www.ncbi.nlm.nih.gov/gene/7128?report=xml&format=text";


$document_xml = new DOMDocument();

$document_xml->loadXML($url);

$elements = $url->getElementsByTagName('Gene-commentary_heading');

echo $elements;

foreach($element as $node) {

    $GO = $node -> getElementsByTagName('GeneOntology');

    $Int = $node->getElementsByTagName('Interactions');

}

标签: phpxmlnodesixmldomelement

解决方案


我的答案

$esearch_test = "https://www.ncbi.nlm.nih.gov/gene/7128?report=xml&format=text";
$result = file_get_contents($esearch_test);
$xml = simplexml_load_string($result);
$doc = new DOMDocument();
$doc = DOMDocument::loadXML($xml);
$c = 1;
foreach($doc->getElementsByTagName('Gene-commentary_heading') as $node) {
echo "$c: ".$node->textContent."\n";
$c++; 
}

推荐阅读