首页 > 解决方案 > 使用php解析到另一个包含xml子节点的数组

问题描述

<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);
}
?>

提前致谢 !

标签: javascriptphpxml

解决方案


使用 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到结果数组。


推荐阅读