如何从Vue文件提取fields数据生成PHP数组?
从Vue文件的data->fields->fields生成PHP数组
实现思路
- 读取Vue文件内容,通过正则定位到
data()返回值里嵌套的fields数组 - 将JS格式的数组转换为标准JSON格式
- 解析JSON为PHP数组,整理成
key => type的目标结构
完整PHP代码
<?php // 读取目标Vue文件 $vueContent = file_get_contents('/resources/js/Components/NameOfVueFile.vue'); // 正则匹配嵌套的fields数组内容 preg_match('/fields:\s*\[\s*\{.*?fields:\s*(\[.*?\])\s*\}\s*\]/s', $vueContent, $matches); if (!empty($matches[1])) { // 将JS语法转换为标准JSON格式 $jsonStr = str_replace(["'", 'null'], ['"', 'null'], $matches[1]); // 解析为PHP关联数组 $rawFields = json_decode($jsonStr, true); // 生成目标格式的数组 $formFields = []; foreach ($rawFields as $field) { $formFields[$field['key']] = $field['type']; } // 输出或使用数组 var_export($formFields); } else { echo "未找到目标fields区域"; } ?>
代码说明
- 正则匹配:
/fields:\s*\[\s*\{.*?fields:\s*(\[.*?\])\s*\}\s*\]/s专门匹配Vue文件中data()里最外层fields数组内的嵌套fields,s修饰符确保跨行匹配 - 格式转换:将JS中的单引号替换为JSON要求的双引号,保留
null以便json_decode正确解析 - 数组整理:遍历解析后的数组,提取每个字段的
key和type,生成符合需求的PHP数组
测试结果
针对你提供的示例Vue文件,运行代码后会输出:
array ( 'title' => 'text', 'code' => 'text', 'include_in_totals' => 'toggle', 'payment_reference' => 'text', )
内容的提问来源于stack exchange,提问作者Matyhaty
相关产品推荐
相关产品推荐

