gpt4 book ai didi

php - 使用PHP在内部解码多个xml标签

转载 作者:可可西里 更新时间:2023-11-01 12:47:39 25 4
gpt4 key购买 nike

我正在寻找一种在字符串中解码多个 XML 标记的“智能方式”,我有以下功能:

function b($params) {
$xmldata = '<?xml version="1.0" encoding="UTF-8" ?><root>' . html_entity_decode($params['data']) . '</root>';
$lang = ucfirst(strtolower($params['lang']));
if (simplexml_load_string($xmldata) === FALSE) {
return $params['data'];
} else {
$langxmlobj = new SimpleXMLElement($xmldata);

if ($langxmlobj -> $lang) {
return $langxmlobj -> $lang;
} else {
return $params['data'];
}
}
}

尝试

$params['data'] = '<French>Service DNS</French><English>DNS Service</English> - <French>DNS Gratuit</French><English>Free DNS</English>';
$params['lang'] = 'French';
$a = b($params);
print_r($a);

但是输出:

Service DNS

我希望它基本上输出每个标签,所以结果应该是:

Service DNS - DNS Gratuit

拔掉我的头发。任何快速帮助或指示将不胜感激。


编辑:细化需求。

看来我还不够清楚;所以让我再举一个例子

如果我有以下字符串作为输入:

The <French>Chat</French><English>Cat</English> is very happy to stay on stackoverflow 
because it makes him <French>Heureux</French><English>Happy</English> to know that it
is the best <French>Endroit</French><English>Place</English> to find good people with
good <French>Réponses</French><English>Answers</English>.

因此,如果我使用“French”运行函数,它将返回:

The Chat is very happy to stay on stackoverflow 
because it makes him Heureux to know that it
is the best Endroit to find good people with
good Réponses.

还有“英语”:

The Cat is very happy to stay on stackoverflow 
because it makes him Happy to know that it
is the best Place to find good people with
good Answers.

希望现在更清楚了。

最佳答案

基本上,我会先解析出 lang 部分,比如:

<French>Chat</French><English>Cat</English>

用这个:

"@(<($defLangs)>.*?</\\2>)+@i"

然后通过回调解析出正确的 lang str。

如果你有 php 5.3+,那么:

function transLang($str, $lang, $defLangs = 'French|English')
{
return preg_replace_callback ( "@(<($defLangs)>.*?</\\2>)+@i",

function ($matches) use($lang)
{
preg_match ( "/<$lang>(.*?)<\/$lang>/i", $matches [0], $longSec );

return $longSec [1];
}, $str );
}

echo transLang ( $str, 'French' ), "\n", transLang ( $str, 'English' );

如果不是,有点复杂:

class LangHelper
{

private $lang;

function __construct($lang)
{
$this->lang = $lang;
}

public function callback($matches)
{
$lang = $this->lang;

preg_match ( "/<$lang>(.*?)<\/$lang>/i", $matches [0], $subMatches );

return $subMatches [1];
}

}

function transLang($str, $lang, $defLangs = 'French|English')
{
$langHelper = new LangHelper ( $lang );

return preg_replace_callback ( "@(<($defLangs)>.*?</\\2>)+@i",
array (
$langHelper,
'callback'
), $str );
}

echo transLang ( $str, 'French' ), "\n", transLang ( $str, 'English' );

关于php - 使用PHP在内部解码多个xml标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20542979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com