获取要在查询中使用的<doc> xml元素的值

时间:2018-07-06 13:16:36

标签: php laravel

我有这个代码

 $xml = $mbpay->processPaymentInfo();
 Log::info('Showing $mbpay:' . var_export($xml, true));

日志显示如下:

[2018-07-06 12:40:56] local.INFO: Showing $mbpay: '<?xml version="1.0" encoding="ISO-8859-1" ?>
<getmb_id>
 <status>ok</status>
<!---->
 <doc>000...</doc>
</getmb_id>'

使用此xml,我想从notifications表中获取列“ r_id”的值,其中“ doc”列的值等于“ doc上方$xml的元素。

您知道如何正确获取xml元素的值,以便可以进行查询以获取r_id吗?

查询应类似于“ $rID = Notifications::where('doc', $doc)->pluck('r_id')->first(); ”,但如何获取$doc

已更新:

    $mbpay = new MBPay($payment_info);

    $processed_payment = $mbpay->processPaymentInfo();
    $xml = simplexml_load_string($processed_payment);
    $doc = $xml->doc;

    $rID = DB::table('notifications')->where('doc', $doc)->pluck('r_id')->first();

    Log::info('Showing $mbpay: ' . var_export($xml, true));
    Log::info('doc: ' . var_export($doc, true)); // shows SimpleXMLElement::__set_state(array(
))
    Log::info('rID: ' . var_export($rID, true)); // shows NULL
    Log::info('xml: ' . var_export($xml, true));

    return \Response::make($xml, '200')->header('Content-Type', 'text/xml');

$mbpay->processPaymentInfo()显示如下:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<getmb_key>
     <status>ok</status>
     <message>...</message>
     <user>...</user>
     <doc>...</doc>
</getmb_key>

1 个答案:

答案 0 :(得分:0)

假设您只希望拥有一个doc节点,则可以通过几种方法获取该节点的价值。首先想到的是simplexml_load_string()

$processed_payment = $mbpay->processPaymentInfo();
$xml = simplexml_load_string($processed_payment);
$doc = (string) $xml->doc;

我们还可以使用DOMDocument's loadXML()进行解析:

$dom = new \DOMDocument();
$dom->loadXML($processed_payment);
$docs = $dom->getElementsByTagName('doc');
$doc = $docs->item(0)->nodeValue;

以及SimpleXMLElement ::

$element = new \SimpleXMLElement($processed_payment);
$doc = (string) $element->doc[0];

最后,有一个很好的带有preg_match的旧正则表达式:

$result = preg_match("/<doc>(.*?)<\\/doc>/", $processed_payment, $matches);
var_dump($matches[1]);

您使用哪种方法取决于文档的结构,并且在某种程度上取决于您的个人喜好。对我来说,simplexml_load_string()是我想到的第一件事,但是在考虑了替代方案并了解了预期的结构后,我认为我更喜欢SimpleXMLElement()

Here are working examples of each method above.