简体   繁体   中英

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

this is my array(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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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