【问题标题】:parsing xml data return empty value in php解析xml数据在php中返回空值
【发布时间】:2017-06-08 12:04:05
【问题描述】:

我正在尝试使用 php 中的 simple_load_string 函数解析 xml 中的数据,它在 $parsed (data parsed) 中返回一个空数据。

要解析的数据是这样的:

<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
    <cas:authenticationSuccess>
        <cas:user>yassine458</cas:user>
    </cas:authenticationSuccess>
</cas:serviceResponse>

是否可以用这种格式解析数据,或者有其他方法可以做到这一点。

这是我的代码:

$xml = simplexml_load_string($result);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$parsed= simplexml_load_string($result);

我正在尝试将其转换为 json 格式

【问题讨论】:

  • 向我们展示代码和数据
  • 你可以看看
  • 有没有解决办法?
  • 这不是有效的 XML,所以很难说更多,因为我无法测试它
  • 我可以得到没有解决方案来解析它?

标签: php xml xml-parsing


【解决方案1】:

当我使用 xml 时,我遇到了同样的问题,但我找到了这个解决方案,它对我有用

文档:-https://github.com/rentpost/xml2array

https://packagist.org/packages/verdant/xml2array

使用

    $xml = '<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
        <cas:authenticationSuccess>
            <cas:user>yassine458</cas:user>
        </cas:authenticationSuccess>
    </cas:serviceResponse>';

    $xml2array = XML2Array::createArray($xml);
    echo "<pre>";
    print_r($xml2array);
    echo "<pre>";

访问“用户”

    echo $xml2array['cas:serviceResponse']['cas:authenticationSuccess']['cas:user'];

结果:-

    Array
    (
        [cas:serviceResponse] => Array
            (
                [cas:authenticationSuccess] => Array
                    (
                        [cas:user] => yassine458
                    )

            )

    )

如果您不想要cas:,只需在 xml 中将其替换为 "";

经过测试sendbox

【讨论】:

【解决方案2】:
$xml_string = file_get_contents('/path');
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

那么你就可以随意使用$json或者$array了。

【讨论】:

    【解决方案3】:

    我找到了这个解决方案:

    $todelete="xmlns:cas=\"http://www.yale.edu/tp/cas\"";
    
            $result="<cas:serviceResponse xmlns:cas=\"http://www.yale.edu/tp/cas\">
                        <cas:authenticationSuccess>
                         <cas:user>pdurant2</cas:user>
                          </cas:authenticationSuccess>
                            </cas:serviceResponse>";
            if (strpos($result, $todelete) !== false) {
                $result= str_replace($todelete,null,$result);
            }
            if (strpos($result, "cas:") !== false) {
                $result= str_replace("cas:",null,$result);
    
            }
            if (strpos($result, "/cas:") !== false) {
                $result= str_replace("/cas:",null,$result);
    
            }
            $parsed=simplexml_load_string($result);
    

    它对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      相关资源
      最近更新 更多