【问题标题】:How to access attributes and values from the output xml result in php如何从 php 中的输出 xml 结果访问属性和值
【发布时间】:2019-01-25 16:35:11
【问题描述】:

我正在通过第三方提供的 API 将支付网关集成到我的网站中,并且我确实成功了。当它处理付款并在所谓的success.php 页面中返回成功结果时,我会从他们的simplexml_load_string($result) 收到已经输出的 xml,它会像这样在success.php 页面中打印出来。

SimpleXMLElement Object
(
[error_code] => 00
[token] => 1182263526325de72aw828369e7aa
[description] => SimpleXMLElement Object
    (
    )

[transaction_status] => 00
[receiver_email] => myemail@gmail.com
[order_code] => 3212423
[total_amount] => 200
[payment_method] => SimpleXMLElement Object
    (
    )

[bank_code] => NLAZ
[payment_type] => 1
[order_description] => SimpleXMLElement Object
    (
    )

[tax_amount] => 0
[discount_amount] => 0
[fee_shipping] => 0
[return_url] => success.php
[cancel_url] => order.php
[buyer_fullname] => eric phuong
[buyer_email] => eric@domain.com
[buyer_mobile] => 012108609
[buyer_address] => abc
[affiliate_code] => SimpleXMLElement Object
    (
    )

[transaction_id] => 12345
)

我想做的是:

  1. 将上面的输出结果放入一个变量中,以便我可以获取值。我怎样才能在 php 和 .php 中做到这一点?我应该这样写还是怎么写?:

    00 …… XML; ?>

  2. 尝试获取所有值,例如buyer_mobile, buyer_email, etc,即012108609, eric@domain.com, etc

你能帮忙吗?

谢谢,

埃里克

P/S:我也尝试阅读此条目https://stackoverflow.com/questions/25522047/php-xml-to-array-object-with-attributes-and-values并应用它,但没有成功。

注意:我已经知道如何解析 xml 文件以获取数组值,但是在这种情况下的过程是完全不同的,它已经在 success.php 页面中输出并回显了。我试图获得价值,但这似乎超出了我的知识范围。 如果问题对您来说不够清楚,我可以根据要求进行更新。

【问题讨论】:

    标签: php xml


    【解决方案1】:

    你可以从simplexml_load_string($result)的返回中获取SimpleXMLElement

    然后您可以访问属性并将它们转换为字符串,因为SimpleXMLElement 有一个__toString 方法。

    $variable = simplexml_load_string($result);
    $buyerMobile = (string)$variable->buyer_mobile;
    $buyerEmail = (string)$variable->buyer_email;
    

    如果您想从该响应中获取值,您可以使用带有alternation 的正则表达式并使用\K 来重置报告匹配的起点:

    \[buyer_(?:email|mobile|fullname|address)\] =>\s*\K.*

    Demo

    【讨论】:

    • 完美运行。关键是我必须阅读他们返回的 $variable 并直接从 success.php 页面解析它。如果我复制如上所示的输出并将其保存在一个全新的 .php 页面中,我无法解析它。谢谢
    • 非常感谢@第四只鸟
    猜你喜欢
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    相关资源
    最近更新 更多