用php删除json变量中的一些信息 [英] Delete some informations in a json variable with php
问题描述
我的问题是我正在解析XML文件,并且此文件包含一些我不想导出为JSON数据的信息.就我而言,我想要一个从第一个[[] caratere返回json数据的函数 这是php代码:
My problem is that i am parsing an XML file and this file contain some information that i don't want to exporting as JSON data. In my case i want a function that return the json data from the first '[' caratere this is the php code:
<?php
class XmlToJsonConverter {
public function ParseXML ($url) {
$fileContents= file_get_contents($url);
// Remove tabs, newline, whitespaces in the content array
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$myXml = simplexml_load_string($fileContents);
$json = json_encode($myXml);
return $json;
}
}
//Path of the XML file
$url= 'http://www.lequipe.fr/rss/actu_rss_Football.xml';
//Create object of the class
$jsonObj = new XmlToJsonConverter();
//Pass the xml document to the class function
$myjson = $jsonObj->ParseXMl($url);
print_r ($myjson);
?>
这是JSON结果的一部分:
this is a part of the JSON result :
{"@ attributes":{"version":"2.0"},"channel":{"title":"L'Equipe.fr Actu Football","link":"http://www.lequipe .fr",描述":"L'Equipe.fr,足球足球",语言":"fr",版权":版权L'Equipe.fr","pubDate": 星期三,2015年4月22日16:31:08 +0200",图片":{"url":"http://www.lequipe.fr/rss/logo_RSS.gif",标题":"L'Equipe .fr," link:" http://www.lequipe.fr," width:" 119," height:" 28}," item:[{" title:" Foot-查
{"@attributes":{"version":"2.0"},"channel":{"title":"L'Equipe.fr Actu Football","link":"http://www.lequipe.fr","description":"L'Equipe.fr, Toute l'actualit\u00e9 du football","language":"fr","copyright":"Copyright L'Equipe.fr","pubDate":"Wed, 22 Apr 2015 16:31:08 +0200","image":{"url":"http://www.lequipe.fr/rss/logo_RSS.gif","title":"L'Equipe.fr","link":"http://www.lequipe.fr","width":"119","height":"28"},"item":[{"title":"Foot - Cha
我希望结果从"["
谢谢
推荐答案
在对json进行编码之前,删除不需要的每个属性:
Remove every attribute you don't want just before encoding json:
public function ParseXML ($url) {
$fileContents= file_get_contents($url);
// Remove tabs, newline, whitespaces in the content array
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$myXml = simplexml_load_string($fileContents);
//--------------
unset($myXml['@attributes']);
unset($myXml['channel']);
unset($myXml['image']);
//--------------
$json = json_encode($myXml);
return $json;
}
或者如果您仅需要以下物品:
or if you only need the item:
public function ParseXML ($url) {
$fileContents= file_get_contents($url);
// Remove tabs, newline, whitespaces in the content array
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$myXml = simplexml_load_string($fileContents);
//--------------
$json = json_encode($myXml['item']);
return $json;
}
这篇关于用php删除json变量中的一些信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!