有谁有想法吗?我对此一无所知。
您将 XML 文本作为 XML 加载到XML 解析器中,例如作为文档元素/根元素的一部分。然后遍历该元素的所有子节点并决定:
- 每个元素,你算 +1
- 对于每个文本,您 + 通过计算该文本中的单词(请参阅其他问答材料如何计算文本中的单词)
当你完成迭代后,你就有了字数。
示例代码:
<?php
/**
* Count Words on XML Text Using PHP
* @link https://stackoverflow.com/a/17670772/367456
*/
$xmlText = <<<BUFFER
The <tag1>quick brown fox</tag1> <tag2>jumps over</tag2>
the lazy <tag1>dog</tag1>
BUFFER;
$doc = new DOMDocument();
$result = $doc->loadXML(sprintf('<root>%s</root>', $xmlText));
if (!$result) {
throw new Exception('Invalid XML text given.');
}
/**
* replace this function with your own implementation that works
* for all your UTF-8 strings, this is just a quick example mock.
*/
function utf8_count_words($string) {
return (int)str_word_count($string);
}
$wordCount = 0;
foreach ($doc->documentElement->childNodes as $node) {
switch ($node->nodeType) {
case XML_ELEMENT_NODE:
$wordCount++;
break;
case XML_TEXT_NODE:
$wordCount += utf8_count_words($node->data);
break;
default:
throw new Exception(
sprintf('Unexpected nodeType in XML-text: %d', $node->nodeType)
);
}
}
printf("Result: %d words.\n", $wordCount);
示例输出(演示):
Result: 6 words.