How to parse this string to json or array format in PHP?

时间:2018-01-11 08:37:06

标签: php error-handling

This is a return from Google Adwords API

Details: [fieldPath: id; trigger: Invalid predicate name: id; errorString: SelectorError.INVALID_PREDICATE_FIELD_NAME]

I would like to parse it to json/array like this:

"Details": {
 "fieldPath": "id", 
 "trigger": "Invalid predicate", 
 "name": "id", 
 "errorString": "SelectorError.INVALID_PREDICATE_FIELD_NAME"
}

2 个答案:

答案 0 :(得分:2)

我认为您需要为这些消息格式创建解析器。这有点hacky解决方案,但您可以将该格式转换为json格式,然后json_decode它。一般的想法:

  1. 在方括号中找到包含它们的任何内容(正则表达式:([[]。* []])$
  2. 替换“;”用“,”
  3. 为字符串值添加引号
  4. json_decode(结果)
  5. 但我会先调查他们的(google's)api,他们可能会选择以json的形式检索数据

答案 1 :(得分:1)

您可以使用str_replace将字符串转换为可解析的格式。然后parse_str进入一个数组。它不能保证适用于所有返回的字符串,但可以回答您的问题。

<?php
$str = 'Details: [fieldPath: id; trigger: Invalid predicate name: id; errorString: SelectorError.INVALID_PREDICATE_FIELD_NAME]';

// strip out details and []
$str = str_replace(['[',']', 'Details:'], '', $str);

// fix name and replace seperators
$str = str_replace([': ', ';', ' name='], ['=', '&', '&name='], $str);

// parse string into $array variable
parse_str($str, $array);

$json = ['Details' => $array];

print_r(json_encode($json, JSON_PRETTY_PRINT));

https://3v4l.org/nKa6b

<强>结果:

{
    "Details": {
        "fieldPath": "id",
        "trigger": "Invalid predicate",
        "name": "id",
        "errorString": "SelectorError.INVALID_PREDICATE_FIELD_NAME"
    }
}