使用PHP从xml文件中提取模式?

时间:2016-02-11 09:31:13

标签: php xml find pattern-matching

我有一个远程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);

3 个答案:

答案 0 :(得分:2)

您可以更好地使用XPath来读取XML文件。 XPath是DOMDocument的变体,专注于读取和编辑XML文件。您可以使用基于简单Unix路径语法的模式查询XPath变量。因此//表示任意位置,./表示相对于所选节点。 XPath->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;
}

答案 1 :(得分:1)

使用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]);

答案 2 :(得分:-1)

你可以尝试这个,它基本上只是循环遍历文件的每一行,并找到XML <unico>标签之间的任何内容。

<?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);

这是你想要的吗? :)

相关问题