【问题标题】:How to get the list of all row from xml file with PHP [duplicate]如何使用PHP从xml文件中获取所有行的列表[重复]
【发布时间】:2018-03-25 03:11:07
【问题描述】:

我有一个 xml 文件,我想解析这个 XML 文件中的作者列表。

            <AuthorList CompleteYN="Y">
            <Author ValidYN="Y">
                <LastName>Goyette-Desjardins</LastName>
                <ForeName>Guillaume</ForeName>
                <Initials>G</Initials>
                <AffiliationInfo>
                    <Affiliation>University 1.</Affiliation>
                </AffiliationInfo>
            </Author>
            <Author ValidYN="Y">
                <LastName>Auger</LastName>
                <ForeName>Jean-Philippe</ForeName>
                <Initials>JP</Initials>
                <AffiliationInfo>
                    <Affiliation>University 2</Affiliation>
                </AffiliationInfo>
            </Author>
            <Author ValidYN="Y">
                <LastName>Xu</LastName>
                <ForeName>Jianguo</ForeName>
                <Initials>J</Initials>
                <AffiliationInfo>
                    <Affiliation>University 3</Affiliation>
                </AffiliationInfo>
            </Author>
        </AuthorList>

我使用此代码获取具有LastnameInitial 的作者姓名,但我的代码仅获得了最后一位作者 (Xu J)。

$api_xml_url = "https://example.com&pid=3123133213&retmode=xml";                            
$xml = file_get_contents($api_xml_url); 
        preg_match_all("'<LastName>(.*?)</LastName>'si", $xml, $match);
        foreach($match[1] as $LastName) {
        $LastName = strip_tags($LastName);
        }
        preg_match_all("'<Initials>(.*?)</Initials>'si", $xml, $match);
        foreach($match[1] as $Initials) {
        $Initials = strip_tags($Initials);
        }
        $authors = $LastName.$Initials;     

如何 获取完整的作者列表(Goyette-Desjardins G;Auger JP;Xu J)。非常感谢

【问题讨论】:

  • 不,要解析 xml 文件,您不必使用正则表达式或任何直接字符串方法。使用 XMLReader 或 DOMDocument。该文件已经结构化,请使用该结构。

标签: php xml parsing preg-match-all


【解决方案1】:

您不应使用正则表达式来解析 XML,而应使用 simplexml_load_string() 之类的东西。

<?php
$api_xml_url = "https://example.com&pid=3123133213&retmode=xml";                            
$string = file_get_contents($api_xml_url);

$xml = simplexml_load_string($string);

foreach ($xml as $item) {
    echo $item->ForeName.' '.$item->LastName.' ('.$item->Initials.')'.PHP_EOL;
}

https://3v4l.org/FeTsa

结果:

Guillaume Goyette-Desjardins (G)
Jean-Philippe Auger (JP)
Jianguo Xu (J)

【讨论】:

  • 请注意,您可以使用simplexml_load_file 函数代替file_get_contents
  • 感谢@Lawrence,但我想将列表放在foreach 旁边,我该怎么办?谢谢
  • 你的意思是你想要一个$authors的数组吗?
  • @NguyenHoangBach;将每个项目存储到一个数组中。有什么问题?
  • 谢谢大家,代码比治疗病人更复杂。 (^^)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-11
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 2012-08-06
  • 2023-02-09
相关资源
最近更新 更多