我是PHP的新手,我有一个xml文件,我想使用PHP将xml文件中的句子提取到数组中,以使句子每次分解为3个单词.句子将分为几部分.
下面的XML来自XML文件.
<?xml version="1.0" encoding="utf-8" ?>
<document>
<content>
<segment>
<sentence>
<word>Hi</word>
<word>there</word>
<word>people</word>
<word>I</word>
<word>want</word>
<word>to</word>
<word>introduce</word>
<word>you</word>
<word>to</word>
<word>my</word>
<word>world</word>
</sentence>
<sentence>
<word>Hi</word>
<word>there</word>
<word>people</word>
<word>I</word>
<word>want</word>
<word>to</word>
<word>introduce</word>
<word>you</word>
<word>to</word>
<word>my</word>
<word>world</word>
</sentence>
</segment>
</content>
</document>
输出将是:
Hi there people
I want to
introduce you to
my world
Hi there people
I want to
introduce you to
my world
function loadTranscript($xml) {
$getfile = file_get_contents($xml);
$arr = simplexml_load_string($getfile);
foreach ($arr->content->segment->sentence as $sent) {
$count = str_word_count($sent,1);
$a=array_chunk($count,3);
foreach ($a as $a){
echo implode(' ',$a);
echo PHP_EOL;
}
}
}
但是无法产生输出. $sent被认为是数组吗?我想在XML级别打断句子.
解决方法:
我不确定为什么每个人都这么害怕SimpleXML,并且我认为它绝对是完成这项工作的正确工具.
$sent不是数组,而是表示< sentence>的对象.元素及其所有子元素;它具有一些类似数组的属性,但没有array_chunk可以使用的属性.
您实际上可以使用array_chunk,但是需要做三件事才能使当前代码正常工作:
>使用(array)$sent(将给出< sentence>节点的所有子元素的数组)或(array)$sent->单词(将其限制为称为< ; word>(如果有混合的话)
>将该数组传递给array_chunk,而不是$count(您不需要)
>不要两次使用具有相同含义的相同变量(foreach($a as $a))
所以:
$chunks = array_chunk((array)$sent->word, 3);
foreach ($chunks as $a_chunk) {
echo implode(' ', $a_chunk);
echo PHP_EOL;
}
另外,您也可以通过仅每三个字显示一个换行符来轻松地完成array_chunk的操作:
$counter = 0;
foreach ( $words as $word ) {
$counter++;
echo $word;
if ( $counter % 3 == 0 ) {
echo PHP_EOL;
} else {
echo ' ';
}
}
然后,您需要做的就是在现有的循环中嵌套:
foreach ($arr->content->segment->sentence as $sent) {
$counter = 0;
foreach ( $sent->word as $word ) {
$counter++;
echo $word;
if ( $counter % 3 == 0 ) {
echo PHP_EOL;
} else {
echo ' ';
}
}
echo PHP_EOL;
}
取决于您自己,他们认为自己更干净,但是最好了解两者,以便您可以使它们适应未来的需求.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。