【问题标题】:Extract pattern from xml file using PHP?使用PHP从xml文件中提取模式?
【发布时间】:2016-02-11 09:31:12
【问题描述】:

我有一个远程 XML 文件。我需要阅读,找到一些值并将它们保存在数组中。

我已经加载了文件(这没问题):

$xml_external_path = 'http://example.com/my-file.xml';
$xml = file_get_contents($xml_external_path);

在这个文件中有很多实例:

<unico>4241</unico>
<unico>234</unico>
<unico>534534</unico>
<unico>2345334</unico>

我只需要提取这些字符串的数量并将它们保存在一个数组中。我想我需要使用这样的模式:

$pattern = '/<unico>(.*?)<\/unico>/';

但我不确定下一步该做什么。请记住,它是一个 .xml 文件。

结果应该是这样的填充数组:

$my_array = array (4241, 234, 534534,2345334);

【问题讨论】:

  • 你用什么语言编程?请添加适当的标签。
  • 一个好建议:记住它是一个 .xml 文件。 我们使用什么工具来处理 XML 中的数据?我猜是 XML 解析器。
  • 我刚刚更新了我的问题:PHP

标签: php xml find pattern-matching


【解决方案1】:

您可以更好地使用 XPath 来读取 XML 文件。 XPath 是 DOMDocument 的变体,专注于读取和编辑 XML 文件。您可以使用基于简单 Unix 路径语法的模式查询 XPath 变量。所以// 表示任何地方,./ 表示相对于选定节点。 XPath-&gt;query() 将根据模式返回带有所有节点的DOMNodelist。下面的代码会做你想做的事:

$xmlFile = "
<unico>4241</unico>
<unico>234</unico>
<unico>534534</unico>
<unico>2345334</unico>";

$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xmlFile);
$xpath = new DOMXPath($xmlDoc);

// This code returns a DOMNodeList of all nodes with the unico tags in the file.
$unicos = $xpath->query("//unico");

//This returns an integer of how many nodes were found that matched the pattern
echo $unicos->length;

您可以在此处找到有关 XPath 及其语法的更多信息:XPath on Wikipedia#syntax

DOMNodeList 实现了 Traversable,所以你可以使用 foreach() 来遍历它。如果你真的想要一个平面数组,你可以简单地使用question #15807314中的简单代码进行转换:

$unicosArr = array();
foreach($unicos as $node){
    $unicosArr[] = $node->nodeValue;
}

【讨论】:

    【解决方案2】:

    使用 preg_match_all:

    <?php
    $xml = '<unico>4241</unico>
    <unico>234</unico>
    <unico>534534</unico>
    <unico>2345334</unico>';
    
    $pattern = '/<unico>(.*?)<\/unico>/';
    
    preg_match_all($pattern,$xml,$result);
    print_r($result[0]);
    

    【讨论】:

    • 很确定preg_match_all() 不会工作,因为在unico标签前后有一些东西。
    • 不知道你到底是什么意思,但正则表达式模式应该提取标签内的内容
    【解决方案3】:

    你可以试试这个,它基本上只是遍历文件的每一行并找到 XML &lt;unico&gt; 标记之间的任何内容。

    <?php
    
    $file = "./your.xml";
    $pattern = '/<unico>(.*?)<\/unico>/';
    $allVars = array();
    
    $currentFile = fopen($file, "r");
    if ($currentFile) {
        // Read through file
        while (!feof($currentFile)) {
            $m_sLine = fgets($currentFile);
            // Check for sitename validity
            if (preg_match($pattern, $m_sLine) == true) {
                $curVar = explode("<unico>", $m_sLine);
                $curVar = explode("</unico>", $curVar[1]);
                $allVars[] = $curVar[0];
            }
        }
    }
    fclose($currentFile);
    print_r($allVars);
    

    这是你想要的吗? :)

    【讨论】:

    • 我得到了数组,但里面没有值。
    • 奇怪,它对我来说很好用。 image能否提供XML文件的内容?
    • 我不能用真正的 xml 做到这一点。我将创建一个示例并在此处发布。
    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    相关资源
    最近更新 更多