Simplexml PHP - 获取“深层节点”的值


Simplexml PHP - get value of a "deep node"

这让我发疯了。我本可以复制并粘贴我需要的 2 个值,并在 30 分钟前完成此操作,但我正在尝试"正确"地执行此操作。

整个文件中只有一个"用户名"。我如何获得它?我尝试使用 xpath ( $username=$xml->xpath('default_setup/connection/username'); ),并尝试将节点链接到它 ( $username=$xml->{...完整路径在这里...}->default_setup->连接->用户名;' )。

当我print_r($xml)时,我可以看到我想要的所有节点及其值。当我print_r($username)时,我什么也得不到。

<?php
$xml = simplexml_load_file('database.xml',NULL,LIBXML_NOCDATA); // connection details are inside of CDATA
$username=$xml->xpath('default_setup/connection/username'); ?>
<p>Username: <?= (string)$username ?></p><?php // outputs "Array"
<?php
foreach($xml as $element) {
        echo $element . '<br />'; // outputs '<br />' 2 times.
}
?>
<pre>
Username:
<?php print_r($username) ?><?php // nothing ?>
xml:
<?php print_r($xml) ?><?php // full set of all nodes with everything I need just out of reach ?>
</pre>

下面是示例 xml。 (它实际上是Magento"app/etc/local.xml"文件)

<default_setup>
    <connection>
        <host><![CDATA[localhost]]></host>
        <username><![CDATA[secret_username]]></username>
        <password><![CDATA[secret_password]]></password>
        <dbname><![CDATA[testing_database]]></dbname>
        <initStatements><![CDATA[SET NAMES utf8]]></initStatements>
        <model><![CDATA[mysql4]]></model>
        <type><![CDATA[pdo_mysql]]></type>
        <pdoType><![CDATA[]]></pdoType>
        <active>1</active>
    </connection>
</default_setup>

您缺少一些您想要的路径链的节点:

$conn = $xml->global->resources->default_setup->connection;
$user = (string) $conn->username;
$pass = (string) $conn->password;

你可以在这里使用 xpath,但它实际上更麻烦,因为它总是会返回一个节点数组(NodeList 的表示形式),所以你必须循环它或使用[0]。仅使用直接访问更容易/更具可读性。也就是说,使用 xpath 执行此操作将是:

$nodes = $xml->xpath('//default_setup/connection');
if (count($nodes) > 0) {
  $conn = $nodes[0];
  $user = (string) $conn->username;
  $pass = (string) $conn->password;
}

来自我的导入程序的完整 xml/连接代码,以防它有帮助:

// get path for config
$config = realpath(dirname(__FILE__) . '/../magento/app/etc/local.xml');
if (!$config) {
    // I've made a terrible mistake.
    throw new Exception('Could not load magento config.');
} else {
    // load up XML
    $conf = new SimpleXMLElement($config, LIBXML_NOCDATA, true);
    // pull the database connection config node
    $conn = $conf->global->resources->default_setup->connection;
    // create a DSN - we will worry about manually setting the attributes ourself
    // since this is a simple one off
    $dsn = sprintf('mysql:host=%s;dbname=%s', $conn->host, $conn->dbname);
    $user = (string) $conn->username;
    $pass = (string) $conn->password;
    $db = new PDO($dsn, $user, $pass);

    if (!$db instanceof PDO) {
        // WOMP, WOMP!
        throw new Exception('Could not create database connection!');
        exit;
    }
}

让我们摆脱您的问题以简化事情。 下面是一个示例。

XML 文件,例如.php:

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;
?>

提取绘图的 php 代码,在您的情况下是用户名:

示例 #2 获取

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
echo $movies->movie[0]->plot;
?>

这来自: http://php.net/manual/en/simplexml.examples-basic.php


没关系,它发生了。

你可以试试这个,特殊值*匹配所有标签。

<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
 <book>Patterns of Enterprise Application Architecture</book>
 <book>Design Patterns: Elements of Reusable Software Design</book>
 <book>Clean Code</book>
</books>
XML;
$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
    echo $book->nodeValue, PHP_EOL;
}
?>

一试。 这是来自 php.net 的网址: http://php.net/manual/en/domdocument.getelementsbytagname.php

如果你看下面,还有更多的例子。