繁体   English   中英

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

[英]Extract pattern from xml file using PHP?

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

您可以更好地使用XPath来读取XML文件。 XPath是DOMDocument的变体,专注于读取和编辑XML文件。 您可以使用模式查询XPath变量,该模式基于简单的Unix路径语法。 所以//表示任何位置,。 ./表示相对于所选节点。 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及其语法的更多信息: Wikipedia#syntax上的XPath

DOMNodeList实现Traversable,因此您可以使用foreach()遍历它。 如果您真的想要一个平面数组,则可以简单地使用诸如问题#15807314的简单代码进行转换:

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

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

您可以尝试一下,它基本上只是遍历文件的每一行,并找到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);

这是您想要的吗? :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM