微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 如何在SimpleXML对象中访问此数字元素?

我正在从我们在Web应用程序中使用的数据源解析XML,并且在访问XML中特定部分的数据时遇到了一些问题.

首先,这是我正在尝试访问的print_r的输出.

SimpleXMLElement Object
(
    [0] => 
This is the value I'm trying to get

)

然后,这是我想要的XML.

<entry>    
    <activity:object>
        <activity:object-type>http://activitystrea.ms/schema/1.0/note</activity:object-type>
        <id>542</id>
        <title>
        Title string is a string
        </title>
        <content>
        This is the value I'm trying to get
        </content>
        <link rel="alternate" type="html" href="#"/>
        <link rel="via" type="text/html" href="#"/>
    </activity:object>
</entry>

内容元素是我追求的.

当我使用$post-> xpath(‘activity:object’)[0] – >内容访问它时,我最终会得到上面的内容.

我尝试过使用$zero = 0;以及 – > content-> {‘0’}来访问此元素,但每次我只返回一个空的SimpleXML对象,如下所示.

SimpleXMLElement Object
(
)

有没有其他方法可以访问我尚未找到的?

谢谢!

解决方法:

您应该只能直接访问它:

$content = $post->xpath('//content');

echo $content[0];

使用PHP 5.4或更高版本,您可以这样做:

$content = $post->xpath('//content')[0]; 

或者,如果您将XML转换为字符串,就像@kkhugs所说,您可以使用

/**
 * substr_delimeters
 *
 * a quickly written, untested function to do some string manipulation for
 * not further dedicated and unspecified things, especially abused for use
 * with XML and from https://stackoverflow.com/a/27487534/367456
 *
 * @param string $string
 * @param string $delimeterLeft
 * @param string $delimeterRight
 *
 * @return bool|string
 */
function substr_delimeters($string, $delimeterLeft, $delimeterRight)
{
    if (empty($string) || empty($delimeterLeft) || empty($delimeterRight)) {
        return false;
    }

    $posLeft = stripos($string, $delimeterLeft);
    if ($posLeft === false) {
        return false;
    }

    $posLeft += strlen($delimeterLeft);

    $posRight = stripos($string, $delimeterRight, $posLeft + 1);
    if ($posRight === false) {
        return false;
    }

    return substr($string, $posLeft, $posRight - $posLeft);
}

$content = substr_delimeters($xmlString, "<content>", "</content>");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐