javascript - 使用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);
}
?>
提前致谢 !
解决方案
使用 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
到结果数组。
推荐阅读
- java - 源模式到目标模式映射框架
- angular - 如何在 Ionic 4 的不同模块中使用 ion-tabs 路由?
- node.js - 只是从 localhost:80 到 localhost:8080 的 nginx 反向代理不起作用
- python - Guizero 的 TextBox.value 在调用 pyplot.figure() 后停止更新
- html - 是否有使用现代 css 样式更改输入元素中闪烁器厚度的解决方案?
- python - 如何在 Python 中存储目标词
- c# - C#实现接口
- javascript - 将回调函数传递给 module.exports?
- google-apps-script - 使用应用程序脚本向上移动日期,但它返回不同的格式?
- postgresql - PostgreSQL 11 共享内存错误:无法打开共享内存段“/PostgreSQL.XXXXXXXX”:没有这样的文件或目录