使用PHP解码多个xml标签

前端之家收集整理的这篇文章主要介绍了使用PHP解码多个xml标签前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一种解码字符串中多个 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",$subMatches );

        return $subMatches [1];
    }

}

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

    return preg_replace_callback ( "@(<($defLangs)>.*?</\\2>)+@i",array (
                    $langHelper,'callback' 
            ),'English' );
原文链接:https://www.f2er.com/php/135721.html

猜你在找的PHP相关文章