簡體   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