PHP将空属性转换为文本或数字

时间:2012-11-16 20:08:52

标签: php xml

我有一个带属性

的xml文件

XML文档

<SET name="John" lastname="Steve" city="New York" Country=""/>

这将转换为包含4个列的CSV文件。

CSV文件

Name,LastName,City,Country
John,Steve,New York,

我想从Country获取Empty内容并转换为默认文本,如USA

我将使用str_replace来替换它。

问题是我不知道如何获取Empty属性,就像是empy var_dump一样。

由于

转换文件。

$filexml = 'file.xml';
    if (file_exists($filexml)){
        $xml = simplexml_load_file($filexml);
$file = fopen('clients.csv', 'w');
        $header = array('Name', 'LastName', 'City', 'Country');
fputcsv($file, $header, ',', '"');
foreach ($xml->SET as $set){
$item = array();
            $value1 = $set->attributes()->name;
            $value2 = $set->attributes()->lastname;
            $value3 = $set->attributes()->city;
            $value4 = $set->attributes()->Country;

$search_country= array('','10','12')
$replace_country = array('USA','Argentina','Canada')
$item[] = $value1;
$item[] = $value2;
$item[] = $value3;
$item[] = str_replace($search_country, $replace_country, $value4);

fputcsv($file, $item, ',', '"');    
        }
        fclose($file);
    }

1 个答案:

答案 0 :(得分:1)

使用empty检查值是否为空

$value4 = empty($set->attributes()->Country) ? "USA" : $set->attributes()->Country;