2014-03-28 35 views
0

我正在循環一個數據庫表,其中包含一些與外部API響應相關的數據。字符串到對象的轉換

有人拯救響應爲文本,就像這樣:

object(stdClass)#5 (1) { 
    ["CreateProspectResult"]=> 
    object(stdClass)#6 (3) { 
    ["State"]=> 
    string(7) "Success" 
    ["ErrorMessage"]=> 
    string(0) "" 
    ["ReturnValue"]=> 
    object(stdClass)#7 (1) { 
     ["ProspectID"]=> 
     int(304) 
    } 
    } 
} 

我猜原來的開發商在做與<pre>標籤一個var_dump(),並從字面上保存的響應。

當我遍歷表結果時,我想將字符串轉換回對象,所以我可以解析它。我失敗了,很糟糕。

這是我已經嘗試:

<?php 

$string = ' 
object(stdClass)#5 (1) { 
    ["CreateProspectResult"]=> 
    object(stdClass)#6 (3) { 
    ["State"]=> 
    string(7) "Success" 
    ["ErrorMessage"]=> 
    string(0) "" 
    ["ReturnValue"]=> 
    object(stdClass)#7 (1) { 
     ["ProspectID"]=> 
     int(304) 
    } 
    } 
} 
'; 

$xmlObj = simplexml_load_string($string); 
echo $xmlObj->CreateProspectResult->State; 
?> 

PHP不享受我的嘗試,給我非對象相關的錯誤回來。

是否有可能採取這樣的字符串並將其轉換回對象?

+0

更新什麼API返回的一個例子您的問題或您不能直接訪問該API。除此之外,我不認爲有任何準備去轉換器從字符串到stdClass。 「 – Prix

+0

」有人將回復保存爲文本,如下所示:「--​​- looooooooool – zerkms

+0

不幸的是,我無法直接訪問API。我被告知回覆是上面發佈的內容。 – coffeemonitor

回答

0

我不是100%確定這是否適用於對象(似乎是),但這似乎涵蓋了您的問題。

function unvar_dump($str) { 
    if (strpos($str, "\n") === false) { 
     //Add new lines: 
     $regex = array(
      '#(\\[.*?\\]=>)#', 
      '#(string\\(|int\\(|float\\(|array\\(|NULL|object\\(|})#', 
     ); 
     $str = preg_replace($regex, "\n\\1", $str); 
     $str = trim($str); 
    } 
    $regex = array(
     '#^\\040*NULL\\040*$#m', 
     '#^\\s*array\\((.*?)\\)\\s*{\\s*$#m', 
     '#^\\s*string\\((.*?)\\)\\s*(.*?)$#m', 
     '#^\\s*int\\((.*?)\\)\\s*$#m', 
     '#^\\s*float\\((.*?)\\)\\s*$#m', 
     '#^\\s*\[(\\d+)\\]\\s*=>\\s*$#m', 
     '#\\s*?\\r?\\n\\s*#m', 
    ); 
    $replace = array(
     'N', 
     'a:\\1:{', 
     's:\\1:\\2', 
     'i:\\1', 
     'd:\\1', 
     'i:\\1', 
     ';' 
    ); 
    $serialized = preg_replace($regex, $replace, $str); 
    $func = create_function(
     '$match', 
     'return "s:".strlen($match[1]).":\\"".$match[1]."\\"";' 
    ); 
    $serialized = preg_replace_callback(
     '#\\s*\\["(.*?)"\\]\\s*=>#', 
     $func, 
     $serialized 
    ); 
    $func = create_function(
     '$match', 
     'return "O:".strlen($match[1]).":\\"".$match[1]."\\":".$match[2].":{";' 
    ); 
    $serialized = preg_replace_callback(
     '#object\\((.*?)\\).*?\\((\\d+)\\)\\s*{\\s*;#', 
     $func, 
     $serialized 
    ); 
    $serialized = preg_replace(
     array('#};#', '#{;#'), 
     array('}', '{'), 
     $serialized 
    ); 

    return unserialize($serialized); 
} 

來源: Convert var_dump of array back to array variable