类XML自定义结构解析为PHP数组方法及更优存储格式咨询
问题1:现有内容是否可以解析为PHP数组?
可以实现,但性价比很低。
你当前存储的内容不属于标准XML格式:没有统一根节点、开头混入独立SVG内容、还存在nav-head/nav-header这类不统一的标签命名,直接用PHP内置的XML解析扩展(比如SimpleXML、DOMDocument)会直接报错。如果一定要解析,要么手动给内容包裹根节点、修正标签错误后再用XML扩展解析,要么写正则匹配对应标签提取内容,但两种方式都存在很高的容错成本,只要存储的内容格式稍有偏差就会解析失败,非常不推荐。
问题2:更优的存储方案推荐
首选JSON格式存储,是当前需求下开发成本最低的方案
PHP内置了json_encode()和json_decode()方法,可以直接实现数组和JSON字符串的无缝转换,完全不需要你自己写任何解析逻辑,使用示例如下:
- 你需要存储的侧边栏结构对应PHP数组格式:
$sidebarConfig = [ // 存储顶部SVG内容 'svg_code' => '<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 125 75"><defs><style>.cls-1{font-size:57.6px;}.cls-1,.cls-2{fill:#f80000;font-family:MicrosoftYaHeiUI-Bold, Microsoft YaHei UI;font-weight:700;}.cls-2{font-size:33.6px;}</style></defs><text class="cls-1" transform="translate(13.28 63.08)">19</text><text class="cls-2" transform="translate(77.56 24.81) scale(0.86 1)">c</text></svg>', // 侧边栏导航分组 'nav_groups' => [ [ 'header' => 'Salamandar', 'posts' => [ ['id' => 12, 'link' => 'url/how-to-pet', 'title' => 'How to Pet'], ['id' => 13, 'link' => 'url/how-to-feed', 'title' => 'How to Feed'], ['id' => 14, 'link' => 'url/salamandar/cage/which-cage', 'title' => 'Which Cages'], ['id' => 17, 'link' => 'url/salamandar/type/different-types', 'title' => 'Types of Salamandar'], ['id' => 19, 'link' => 'url/salamandar/type/poisonous-breed', 'title' => 'Poisonus Breed'] ] ], [ 'header' => 'Keeping Safe', 'posts' => [ ['id' => 21, 'link' => 'url/salamandar/safety/safety-children', 'title' => 'Keep out of Children'], ['id' => 24, 'link' => 'url/salamandar/safety/keep-out-of-dogs', 'title' => 'Keep out of Dogs'], ['id' => 27, 'link' => 'url/salamandar/safety/keep-out-of-reptiles', 'title' => 'Keep out of Reptiles'], ['id' => 34, 'link' => 'url/redis/salamandar/safety/fungus-free', 'title' => 'Keep fungus free'] ] ] ] ];
- 存入数据库前,直接用
json_encode($sidebarConfig)转成字符串存到MySQL的对应字段即可。 - 读取时用
json_decode($读取到的字符串, true)就能直接拿到完整的PHP数组,后续渲染侧边栏加active类时,只需要遍历数组匹配当前访问的文章ID即可,逻辑非常简单。
如果没有跨语言读取数据的需求,也可以用PHP的serialize()方法序列化数组后存储,但兼容性比JSON差,优先选JSON即可。
如果后续需要频繁单独修改某一个导航分组或者某篇文章的配置,也可以拆成MySQL的单独数据表存储,结构更清晰,但如果只是存储完整的侧边栏配置,JSON单字段存储的开发效率最高。
内容的提问来源于stack exchange,提问作者Brown Paul
相关产品推荐
相关产品推荐

