[英]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.