簡體   English   中英

嘗試從API輸出解析XML / JSON

[英]Attempting to parse XML/JSON from an API output

好的......我正在使用PHP 5(溫柔,還在學習PHP)。 CURL已啟用。 嘗試將API或API中的XML或JSON輸出加載到對象,但沒有任何反應。 當我手動執行有問題的URL時,我得到了我期待的東西。

這是我的代碼:

class XmlToJson {
    public function Parse ($url) {
        $fileContents = file_get_contents($url);
        $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
        $fileContents = trim(str_replace('"', "'", $fileContents));
        $simpleXml = simplexml_load_string($fileContents);
        $json = json_encode($simpleXml);
        return $json;
    }
}

$_MySQLServer = "localhost";
$_MySQLServerUserName = "";
$_MySQLServerPassword = "";
$_MySQLDatabaseName = "";

$_SSActiveWear_UserID = "*****";
$_SSActiveWear_APIKey = "*****";
$_SSActiveWear_APIBaseURL = "https://*****/v2";
$_CategoryURL = "/categories/";
$_StylesURL = "/styles/";
$_ProductsURL = "/products/";
$_SpecsURL = "/specs/";
$_SSActiveWear_MediaType = "xml";

//$_conn = mysqli_connect($_MySQLServer, $_MySQLServerUserName, $_MySQLServerPassword, $_MySQLDatabaseName);

//Insert or Update Categories
$_URL = $_SSActiveWear_APIBaseURL . $_CategoryURL;
$_URL = $_URL . "?mediatype=$_SSActiveWear_MediaType&UserName=$_SSActiveWear_UserID&Password=$_SSActiveWear_APIKey";

$OBJ = simplexml_load_string($_URL);

print_r($OBJ);

我究竟做錯了什么?

編輯1

添加了以下代碼:

$xml = simplexml_load_file($_URL) or die("Error: Cannot create object");
print_r($xml);

它死了 這是否意味着代碼有問題?

嘗試這個 :

$OBJ = simplexml_load_string(file_get_contents($_URL));

如果您想知道代碼無效的原因,您嘗試從URL加載XML,但“simplexml_load_string”從字符串加載XML。

我終於想通了......更重要的是,我終於在Google上找到了一個有幫助的網站。 這是fsockopen中第一個帶有http身份驗證問題的答案。

所以這是有效的代碼:

file_get_contents("https://$_SSActiveWear_UserID:$_SSActiveWear_APIKey@$_SSActiveWear_APIBaseURL$_CategoryURL/?mediatype=$_SSActiveWear_MediaType");

mediatype可以是json或xml

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM