如何访问 SimpleXML 对象中的这个数字元素?

Sha*_*ite 5 php xml xpath simplexml

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

print_r首先,这是我尝试访问的内容的输出。

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

)
Run Code Online (Sandbox Code Playgroud)

然后,这是我想要获取的 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>
Run Code Online (Sandbox Code Playgroud)

内容元素就是我所追求的。

当我访问它时,$post->xpath('activity:object')[0]->content我最终得到上面的内容。

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

SimpleXMLElement Object
(
)
Run Code Online (Sandbox Code Playgroud)

还有其他我还没有找到的访问方法吗?

谢谢!

Dem*_*ave 1

您应该能够直接访问它:

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

echo $content[0];
Run Code Online (Sandbox Code Playgroud)

使用 PHP 5.4 或更高版本,您可以执行以下操作:

$content = $post->xpath('//content')[0]; 
Run Code Online (Sandbox Code Playgroud)

或者,如果您将 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 http://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>");
Run Code Online (Sandbox Code Playgroud)