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


Check whether an xml response contains a certain value php

我正在向发送响应xml的服务器发布xml。我的问题是,我不知道如何处理传入的xml(检查"purchased"元素的值,并将用户(基于标准)重定向到"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";
    }
?>

如果能在这个问题上提供任何帮助,我们将不胜感激。

您可以使用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字符串作为一个可以轻松访问的对象。