检查xml响应是否包含某个值php

时间:2014-10-04 13:59:47

标签: php xml response

我将xml发布到发送响应xml的服务器上。我的问题是我不知道如何处理传入的xml(检查'已购买的'元素的值并将用户(基于标准)重定向到' redirect_url'元素) 。这是一个响应代码示例:

<?xml version="1.0" encoding="UTF-8"?>
<result>
    <posting_error>0</posting_error>
    <purchased>1</purchased>
    <redirect_url>http://redirect.php?id=123</redirect_url>
</result>

以下是我的PHP代码片段:

<?php
    # $headercontent is not referencing the response in any way, how would I do this
    # (if need be)?
    if($headercontent->result[0]->purchased == 1)
    {
        #redirect the user to the 'redirect_url' in the response xml 
    }
    else
    {
       echo "the application was unsuccessful";
    }
?>

对此问题的任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以使用simplexml读取生成的XML,如下所示:

<?php
$string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<result>
    <posting_error>0</posting_error>
    <purchased>1</purchased>
    <redirect_url>http://redirect.php?id=123</redirect_url>
</result>
XML;

$result = simplexml_load_string($string);
if (isset($result->purchased))
{
    echo $result->purchased;
}
else
{
    echo "no purchased value is present...";
}

正如名称simplexml_load_string读取一串XML作为您可以轻松访问的对象。