[英]parse into another array contain xml child node using php
目前,即时通讯在使用<mo>
作为分隔符进行解析的条件下无法解析数组中的xml节点
这是我的数组(0)
Array([0] => <mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>);
我想这样解析
Array[0] => <mi>x</mi>
Array[1] =><mo>+</mo><mn>2</mn>
Array[2]=><mo>=</mo><mn>3</mn>
这是我的编码
<? $result(0)="<mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>"; $result1= new simplexml_load_string($result); $arr_result=[]; foreach($result1 as $key => $value){ $exp_key = explode('<', $key); if($key[0] == 'mo'){ $arr_result[] = $value; } print_r($arr_result); } if(isset($arr_result)){ print_r($arr_result); } ?>
提前致谢 !
使用XML的方法似乎过多,因为您真正想要的是基于定界符提取字符串的子字符串。
这是一个工作示例。 它通过找到<mo>
的位置并切断该部分,然后在剩余字符串中搜索下一个<mo>
来工作。
<?php
$result(0)="<mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>";
$res = $result(0);
$arr_result=[];
while($pos = strpos($res, "<mo>", 1)) {
$arr_result[] = substr($res, 0, $pos); // grab first match
$res = substr($res, $pos); // grab the remaining string
}
$arr_result[] = $res; // add last chunk of string
print_r($arr_result);
?>
您上面的代码有几个问题。 第一:
$result1= new simplexml_load_string($result); // simplexml_load_string() is a function not a class
第二:
$key
和$value
不包含'<'和'>',因此,这一部分: $exp_key = explode('<', $key);
永远不会做任何事情,并且是不需要的。
第三:
如果您的代码能够正常工作,则只会返回array('+', '=')
因为您要将mo
元素内部的数据附加到结果数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.