0

简单来说,假设您有以下 xml 结构:

<TEXT>Well, I need some help as you <CUSTOMTAG>can</CUSTOMTAG> see.</TEXT>

在 PHP 中使用 strip_tags() 提取此节点的文本时,我没有得到标签的内容。

第一步:

我想要做的是提取并因此具有以下字符串:

“嗯,正如你所见,我需要一些帮助。”

第二步:

我还想将<CUSTOMTAG>and转换</CUSTOMTAG>为其他东西,例如<e>and </e>,最后得到以下字符串:

"Well, I need some help as you <e>can</e> see."

我只会欣赏经过测试和工作的代码。

提前致谢!

亲切的问候

4

2 回答 2

0

第一步只需使用以下代码:

<?php
$xml = "<TEXT>Well, I need some help as you <CUSTOMTAG>can</CUSTOMTAG> see.</TEXT>";

$domDoc  = new DOMDocument();
$domDoc->loadXML($xml);

$domXPath  = new DOMXPath($domDoc);
$textNodes = $domXPath->query('//TEXT');

foreach ($textNodes as $textNode) {
    echo $textNode->textContent;
}

对于第二步,只需查看此答案https://stackoverflow.com/a/8164058/2000503

于 2013-06-29T18:59:46.387 回答
0

For the second part, you could use something like that:

<?php
$xml = "<TEXT>Well, I need some help as you <CUSTOMTAG>can</CUSTOMTAG> see, <CUSTOMTAG>maybe</CUSTOMTAG>.</TEXT>";

//1st part:
$dom = new DOMDocument();
$dom->loadXML($xml);
$xPath = new DOMXPath($dom);
foreach ($xPath->query('//TEXT') as $textNode) {
  echo $textNode->textContent;
}
// 2nd part:
foreach ($xPath->query('//TEXT/CUSTOMTAG') as $find) {
  $find_value = $find->nodeValue;
  $replace = $dom->createDocumentFragment();
  $replace->appendXML('<e>'.$find_value.'</e>');
  $find->parentNode->insertBefore($replace, $find); 
  $parentnode = $find->parentNode;
  $parentnode->removeChild($find);
}
$result = $dom->saveHTML();
echo $result;
?>
于 2013-06-29T20:37:04.153 回答