加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2021-08-28 03:44:58 所属栏目:大数据 来源: https://www.jb51.cc
导读:我正在从我们在Web应用程序中使用的数据源解析XML,并且在访问XML中特定部分的数据时遇到了一些问题. 首先,这是我正在尝试访问的print_r的输出. SimpleXMLElement Object( [0] = This is the value I'm trying to get) 然后,这是我想要的XML. entry activity:

我正在从我们在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>");

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读