简体   繁体   English

使用php解析为另一个包含xml子节点的数组

[英]parse into another array contain xml child node using php

currently, im having problem to parse xml node in array using condition where parse with <mo> as separator 目前,即时通讯在使用<mo>作为分隔符进行解析的条件下无法解析数组中的xml节点

this is my array(0) 这是我的数组(0)

Array([0] => <mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>);

i want to parse like this 我想这样解析

Array[0] => <mi>x</mi>
Array[1] =><mo>+</mo><mn>2</mn>
Array[2]=><mo>=</mo><mn>3</mn>

this is my coding 这是我的编码

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

thanks in advance ! 提前致谢 !

The approach with XML seems excessive since what you really want is to pull out substrings of a string based on a delimiter. 使用XML的方法似乎过多,因为您真正想要的是基于定界符提取字符串的子字符串。

Here is a working example. 这是一个工作示例。 It works by finding the position of <mo> and cutting off that section, then searching for the next <mo> in the remain string. 它通过找到<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);

?>

Your code above has several issues. 您上面的代码有几个问题。 First: 第一:

$result1= new simplexml_load_string($result); // simplexml_load_string() is a function not a class

Second: 第二:

$key and $value do not contain the '<' and '>' so, this part: $exp_key = explode('<', $key); $key$value不包含'<'和'>',因此,这一部分: $exp_key = explode('<', $key); will never do anything and isn't needed. 永远不会做任何事情,并且是不需要的。

Third: 第三:

If your code did work it would only return array('+', '=') because you are appending the data inside the mo element to the result array. 如果您的代码能够正常工作,则只会返回array('+', '=')因为您要将mo元素内部的数据附加到结果数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM