How to convert XML attributes to text nodes

前端 未结 3 1552
滥情空心
滥情空心 2021-01-25 02:11

I have a PHP script that pulls an XML file from a remote server, and converts it to JSON using simplexml_load_string and json_encode. However, the simplexml_load_string seems t

相关标签:
3条回答
  • 2021-01-25 02:43

    Try this regex: ([\w]*?)="(.*?)" with this replace <$1>$2</$1>\n

    0 讨论(0)
  • 2021-01-25 02:49

    You should use SimpleXML. Be aware though, that you have to cast values to string type explicitly, or you'll get objects.

    $xml_string = <<<XML
    <AxisFeedrate 
    dataItemId="iid7" 
    timestamp="2012-03-21T15:15:41-04:00" 
    sequence="7" 
    name="Yfrt" 
    subType="ACTUAL" 
    units="MILLIMETER/SECOND"
    >UNAVAILABLE</AxisFeedrate>
    XML;
    
    $xml = simplexml_load_string($xml_string);
    
    $axis_info = array('value' => (string)$xml);
    
    foreach($xml -> attributes() as $attr => $val) {
        $axis_info[$attr] = (string) $val;
    }
    
    echo json_encode(array("AxisFeedrate" => $axis_info));
    

    Update:

    This will give you a more generic version, but notice that the attributes are cast as an array and that this only works on a single element:

    $xml_string = <<<XML
    <AxisFeedrate dataItemId="iid7" timestamp="2012-03-21T15:15:41-04:00" sequence="7" name="Yfrt" subType="ACTUAL" units="MILLIMETER/SECOND">UNAVAILABLE</AxisFeedrate>
    XML;
    
    $xml = simplexml_load_string($xml_string);
    
    $obj_name = $xml -> getName();
    
    $attributes = (array) $xml->attributes();
    
    $axis_info[$obj_name] = $attributes["@attributes"];
    $axis_info[$obj_name]['value'] = (string) $xml;
    
    echo json_encode($axis_info);
    
    0 讨论(0)
  • 2021-01-25 03:00

    You could use SimpleXML itself to read the attributes.

    Example:

    <?php
    $xml=simplexml_load_string('<AxisFeedrate dataItemId="iid7" timestamp="2012-03-21T15:15:41-04:00" sequence="7" name="Yfrt" subType="ACTUAL" units="MILLIMETER/SECOND">UNAVAILABLE</AxisFeedrate>');
    
    foreach($xml->attributes() as $k=>$v) {
        echo $k." -> ".(string)$v."\n";
    
    }
    ?>
    


    Output:

    dataItemId -> iid7
    timestamp -> 2012-03-21T15:15:41-04:00
    sequence -> 7
    name -> Yfrt
    subType -> ACTUAL
    units -> MILLIMETER/SECOND
    
    0 讨论(0)
提交回复
热议问题