[英]PHP parsing xml file error
我正在嘗試使用simpleXML從http://rates.fxcm.com/RatesXML獲取數據使用simplexml_load_file()
我有時會遇到錯誤,因為這個網站在xml文件之前和之后總是有奇怪的字符串/數字。 例:
2000<?xml version="1.0" encoding="UTF-8"?>
<Rates>
<Rate Symbol="EURUSD">
<Bid>1.27595</Bid>
<Ask>1.2762</Ask>
<High>1.27748</High>
<Low>1.27385</Low>
<Direction>-1</Direction>
<Last>23:29:11</Last>
</Rate>
</Rates>
0
然后我決定使用file_get_contents並將其解析為帶有simplexml_load_string()
的字符串,之后我使用substr()
來刪除前后的字符串。 但是,有時隨機字符串將出現在節點之間,如下所示:
<Rate Symbol="EURTRY">
<Bid>2.29443</Bid>
<Ask>2.29562</Ask>
<High>2.29841</High>
<Low>2.28999</Low>
137b
<Direction>1</Direction>
<Last>23:29:11</Last>
</Rate>
我的問題是,無論如何我可以使用任何正則表達式函數處理所有這些隨機字符串,無論它們放在何處? (認為這將是一個更好的主意,而不是聯系該網站,讓他們廣播正確的xml文件)
但是這里有一個preg替換,它從字符串的開頭,字符串的結尾以及關閉/自閉標簽之后刪除所有非空白字符:
$string = preg_replace( '~
(?| # start of alternation where capturing group count starts from
# 1 for each alternative
^[^<]* # match non-< characters at the beginning of the string
| # OR
[^>]*$ # match non-> characters at the end of the string
| # OR
( # start of capturing group $1: closing tag
</[^>]++> # match a closing tag; note the possessive quantifier (++); it
# suppresses backtracking, which is a convenient optimization,
# the following bit is mutually exclusive anyway (this will be
# used throughout the regex)
\s++ # and the following whitespace
) # end of $1
[^<\s]*+ # match non-<, non-whitespace characters (the "bad" ones)
(?: # start subgroup to repeat for more whitespace/non-whitespace
# sequences
\s++ # match whitespace
[^<\s]++ # match at least one "bad" character
)* # repeat
# note that this will kind of pattern keeps all whitespace
# before the first and the last "bad" character
| # OR
( # start of capturing group $1: self-closing tag
<[^>/]+/> # match a self-closing tag
\s++ # and the following whitespace
)
[^<]*+(?:\s++[^<\s]++)*
# same as before
) # end of alternation
~x',
'$1',
$input);
然后我們簡單地回寫關閉或自動關閉標簽(如果有的話)。
這種方法不安全的原因之一是在注釋或屬性字符串中可能會出現關閉或自動關閉標記。 但我很難建議您使用XML解析器,因為您的XML解析器也無法解析XML。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.