我得到的 cURL 字符串是这样的:
<!CDATA[[
var animals = new Array();
animals[0] = new Animal('Skunk', 10, 15, 'pic1.png');
animals[1] = new Animal('Dog', 17, 11, 'pic2.png');
animals[2] = new Animal('Gorilla', 144, 95, 'pic3.png');
]]>
等等。我添加新行只是为了更好地说明该字符串的结构。问题是如何使用 PHP 访问:
- 动物数组的值(例如 new Animal('Skunk', 10, 15, 'pic1.png');)
- 函数 Animal 的值(例如“Skunk”、10、15、“pic1.png”)
我只是想在 PHP 中得到这样的东西:
array{
[0] => array([0] => 'Skunk', [1] => 10, [2] => 15, [3] => 'pic1.png')
}
我希望有一些其他解决方案可以爆炸,preg_match等......
感谢您的建议。
最佳答案
回答
没有原生的方法。如果您可以控制被调用的页面,我建议将数据输出为 json 并使用 php 的方法 json_decode($json, true)
。
如果你无法控制它,你有两种可能性:
- 解析字符串
- 搜索 PHP Javascript 解释器,执行 JS 并编码为 Json(这个问题可能开销太大)
因此以下内容将帮助您进行解析。
理论
删除
()
基本上,您将使用此正则表达式提取
(
和)
之间的所有内容/(([^)]+))/
您将按
、
进行拆分
实践
没有测试过这个或检查过 snytax 错误,因为我这里没有 IDE:
//Remove Initializer Brackets
$dataString = str_replace('()', '', $dataString);
//Your final Animal Collection
$animalCollection = [];
//Find each Animal Definition, which is beetween ( and )
preg_match_all('/\(([^)]+)\)/', $dataString, $matches);
foreach ($matches[0] as $match) {
//Explode partes of the animal
$expCollection = explode(',', $match);
//Create a animal array
$animal = [];
foreach ($expCollection as $expPart) {
//Copy the cleaned animal parts to our array
$animal[] = trim(str_replace('\'', '', $expPart));
}
//fill animal Collection
$animalCollection[] = $animal;
}
//Show content
print_r($animalCollection)
关于php - 如何使用 PHP 从 CDATA 字符串读取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24180220/