PHP Parse XML with simplexml_load_file

时间:2015-10-06 08:52:59

标签: php xml

What is the way to parse an XML feed that looks like this:

<string xmlns="http://vs-social-feed/">
{ "response": "success", "message": "", "feed":
[
{"SocialId":105,"Type":2,"Id":"202297433163449_956836567709528","Url":"https://www.facebook.com/vsmag/photos/a.209641845762341.52114.202297433163449/956836567709528/?type=3","Text":"Hold your tongue!\n\nStacy Martin by Ellen von Unwerth official for Vs. Magazine","Other":"\u003ca href=\"https://www.facebook.com/vsmag/photos/a.209641845762341.52114.202297433163449/956836567709528/?type=3\" target=\"_blank\"\u003e\u003cimg src=\"https://graph.facebook.com/956836567709528/picture/\" \" width=\"220\"\u003e\u003c/a\u003e","DateCreate":"\/Date(1444068001000)\/"},
{"SocialId":104,"Type":2,"Id":"202297433163449_956833817709803","Url":"https://www.facebook.com/vsmag/photos/a.209641845762341.52114.202297433163449/956833817709803/?type=3","Text":"Proper posture, ladies!\n\nThe always elegant, Christy Turlington Burns by Patrick Demarchelier","Other":"\u003ca href=\"https://www.facebook.com/vsmag/photos/a.209641845762341.52114.202297433163449/956833817709803/?type=3\" target=\"_blank\"\u003e\u003cimg src=\"https://graph.facebook.com/956833817709803/picture/\" \" width=\"220\"\u003e\u003c/a\u003e","DateCreate":"\/Date(1444075201000)\/"}
]
}
</string>

I have tried with simplexml_load_file, file_get_contents, json_decode and json encode, but without any luck.

1 个答案:

答案 0 :(得分:0)

It is JSON data not XML. PHP has built in json_decode() function to parse json data.

Try this code:

<?php

$data = '{ "response": "success", "message": "", "feed":[{"SocialId":105,"Type":2,"Id":"202297433163449_956836567709528","Url":"https://www.facebook.com/vsmag/photos/a.209641845762341.52114.202297433163449/956836567709528/?type=3","Text":"Hold your tongue!\n\nStacy Martin by Ellen von Unwerth official for Vs. Magazine","Other":"\u003ca href=\"https://www.facebook.com/vsmag/photos/a.209641845762341.52114.202297433163449/956836567709528/?type=3\" target=\"_blank\"\u003e\u003cimg src=\"https://graph.facebook.com/956836567709528/picture/\" \" width=\"220\"\u003e\u003c/a\u003e","DateCreate":"/Date(1444068001000)/"},{"SocialId":104,"Type":2,"Id":"202297433163449_956833817709803","Url":"https://www.facebook.com/vsmag/photos/a.209641845762341.52114.202297433163449/956833817709803/?type=3","Text":"Proper posture, ladies!\n\nThe always elegant, Christy Turlington Burns by Patrick Demarchelier","Other":"\u003ca href=\"https://www.facebook.com/vsmag/photos/a.209641845762341.52114.202297433163449/956833817709803/?type=3\" target=\"_blank\"\u003e\u003cimg src=\"https://graph.facebook.com/956833817709803/picture/\" \" width=\"220\"\u003e\u003c/a\u003e","DateCreate":"/Date(1444075201000)/"}] }';
$obj = json_decode($data);
echo "<pre>"; print_r($obj->feed); echo "</pre>";

?>