如果没有xmllang =“ no”,如果没有回显“ noname”,我正在尝试回显挪威语言。像
000000000121698001,
文本000000000121699001,noname
但这只会返回所有具有 xmllang =“ no” 的产品ID,而不打印没有 xmllang =“ no” 的 productId
XML
<catalog>
<product productid="000000000121698001">
<displayname xmllang="da">text</displayname>
<displayname xmllang="fi">text</displayname>
<displayname xmllang="no">text</displayname>
<displayname xmllang="sv">text</displayname>
</product>
<product productid="000000000121699001">
<displayname xmllang="da">test</displayname>
<displayname xmllang="x-default">test</displayname>
<displayname xmllang="sv">test</displayname>
</product>
PHP
foreach ($xml->product as $product) {
foreach ($product->displayname as $name) {
switch((string) $name['xmllang']) {
case 'no':
echo $product->attributes()->productid. ",";
if (isset($name)){
echo $name. ",", PHP_EOL;
} else {
echo 'noname ,';
}
echo "<br>\n";
}
}
}
答案 0 :(得分:0)
我将其分为两部分:第一,准备数据并找到正确的本地化标签或设置默认值;然后2nd以任何格式输出数据(或理想情况下将$idList
传递到模板)。
<?php
/** @var SimpleXMLElement $xml */
$idList = [];
/* Prepare the data */
foreach ($xml->product as $product) {
$fallbackLabel = null;
/* Iterate over the display names */
foreach ($product->displayname as $name) {
/* And search for the one in a matching language */
switch ((string)$name['xmllang']) {
case 'no':
$idList[$product->attributes()->productid] = $name;
break;
case 'x-default':
$fallbackLabel = $name;
break;
}
}
/* If no name in the searched language was found, set a fallback here */
if (!isset($idList[$product->attributes()->productid])) {
if (!empty($fallbackLabel)) {
/* If a label with a language code of "x-default" was found, use that as fallback label */
$idList[$product->attributes()->productid] = $fallbackLabel;
} else {
/* …if not set a static text */
$idList[$product->attributes()->productid] = 'noname';
}
}
}
/* Output the data */
foreach ($idList as $id => $label) {
echo sprintf("%s,%s<br>\n", $id, $label);
}